package com.yida.gwj.expend.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson2.JSONObject;
import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.utils.ColumnUtil;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.core.utils.PageUtils;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.gwj.api.domain.GwjConfBusinessFlag;
import com.yida.gwj.api.domain.GwjConfFlow;
import com.yida.gwj.api.domain.GwjConfStep;
import com.yida.gwj.api.domain.GwjFinanceAccountMain;
import com.yida.gwj.api.domain.GwjFinanceBank;
import com.yida.gwj.api.domain.GwjMaintenanceFundsBusinessInner;
import com.yida.gwj.api.domain.dto.GwjExpendHouseAndOwnerDTO;
import com.yida.gwj.api.domain.request.RemoteGwjFinanceAccountMainRequest;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.api.service.RemoteGwjExpendService;
import com.yida.gwj.api.service.RemoteGwjFinanceService;
import com.yida.gwj.common.domain.GwjBaseHouse;
import com.yida.gwj.common.domain.mq.MqSendRequest;
import com.yida.gwj.common.domain.mq.MqSendResult;
import com.yida.gwj.common.enums.GwjBusinessFlagType;
import com.yida.gwj.common.enums.GwjBusinessLogResult;
import com.yida.gwj.common.enums.GwjCheckAccountStatus;
import com.yida.gwj.common.enums.GwjCheckAccountType;
import com.yida.gwj.common.enums.StepConfigInfoEnum;
import com.yida.gwj.common.handler.BaseArchiveNumServiceHandler;
import com.yida.gwj.common.handler.MqSendMessageHandler;
import com.yida.gwj.common.service.IGwjBaseHouseService;
import com.yida.gwj.common.utils.GwjEnumUtils;
import com.yida.gwj.common.utils.WeekdayUtils;
import com.yida.gwj.expend.annotation.ConfStepConfigCheck;
import com.yida.gwj.expend.config.MaintenanceFundsBusinessConfiguration;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusiness;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessAttachment;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessBuild;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessCommunity;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessHouse;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessInfo;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessLog;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessOwner;
import com.yida.gwj.expend.domain.dto.AllocatedAmountListDTO;
import com.yida.gwj.expend.domain.dto.AllocatedAmountSelectDTO;
import com.yida.gwj.expend.domain.dto.Application4ApprovalDTO;
import com.yida.gwj.expend.domain.dto.ApplicationReportDTO;
import com.yida.gwj.expend.domain.dto.Appropriate4ApproveDTO;
import com.yida.gwj.expend.domain.dto.ChangeSchemeDTO;
import com.yida.gwj.expend.domain.dto.ConfirmReceiptDTO;
import com.yida.gwj.expend.domain.dto.CostListDTO;
import com.yida.gwj.expend.domain.dto.FilingCertificateDTO;
import com.yida.gwj.expend.domain.dto.GetAttachmentInfoRequest;
import com.yida.gwj.expend.domain.dto.GwjConfStepDTO;
import com.yida.gwj.expend.domain.dto.GwjMaintenanceFundsBusinessBuildDTO;
import com.yida.gwj.expend.domain.dto.GwjMaintenanceFundsBusinessDTO;
import com.yida.gwj.expend.domain.dto.GwjMaintenanceFundsBusinessGetInfoDTO;
import com.yida.gwj.expend.domain.dto.GwjMaintenanceFundsBusinessInfoDTO;
import com.yida.gwj.expend.domain.dto.GwjMaintenanceFundsBusinessListDTO;
import com.yida.gwj.expend.domain.dto.OneTimeNotificationDTO;
import com.yida.gwj.expend.domain.dto.StepConfigInfoDTO;
import com.yida.gwj.expend.domain.message.MaintenanceFundsMqMessageBody;
import com.yida.gwj.expend.domain.message.PreAcceptMessage;
import com.yida.gwj.expend.domain.message.PreAcceptSecondExamineInnerMessage;
import com.yida.gwj.expend.domain.message.PreAcceptSubmitMessage;
import com.yida.gwj.expend.domain.request.AllocatedAmountRequest;
import com.yida.gwj.expend.domain.request.ApplicationReportRequest;
import com.yida.gwj.expend.domain.request.BusinessProcessRequest;
import com.yida.gwj.expend.domain.request.EditFormRequest;
import com.yida.gwj.expend.domain.request.GwjMaintenanceFundsBusinessListRequest;
import com.yida.gwj.expend.domain.request.GwjMaintenanceFundsBusinessRequest;
import com.yida.gwj.expend.domain.request.GwjSaveChangeSchemeRequest;
import com.yida.gwj.expend.domain.request.HousesUnderBuildRequest;
import com.yida.gwj.expend.domain.request.SubmitRequest;
import com.yida.gwj.expend.enums.AppropriationWayEnum;
import com.yida.gwj.expend.enums.BusinessAttachmentServerTypeEnum;
import com.yida.gwj.expend.enums.BusinessAttachmentTypeEnum;
import com.yida.gwj.expend.enums.BusinessModuleTypeEnum;
import com.yida.gwj.expend.enums.BusinessServerStatusEnum;
import com.yida.gwj.expend.enums.BusinessStatusEnum;
import com.yida.gwj.expend.enums.BusinessTypeEnum;
import com.yida.gwj.expend.enums.FilingCertificateEnum;
import com.yida.gwj.expend.enums.FlagStatusEnum;
import com.yida.gwj.expend.enums.MaintenanceFundsErrorEnum;
import com.yida.gwj.expend.enums.SelectFlagEnum;
import com.yida.gwj.expend.mapper.GwjMaintenanceFundsBusinessMapper;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessAttachmentService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessBuildService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessCommunityService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessHouseService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessInfoService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessLogService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessOwnerService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

/**
 * 公维金维修资金业务Service业务层处理
 *
 * @author lgp
 * @date 2023-02-20
 */
@Service
public class GwjMaintenanceFundsBusinessServiceImpl implements IGwjMaintenanceFundsBusinessService {

    private final Logger log = LoggerFactory.getLogger(GwjMaintenanceFundsBusinessServiceImpl.class);
    @Autowired
    private GwjMaintenanceFundsBusinessMapper maintenanceFundsBusinessMapper;
    @Autowired
    private IGwjMaintenanceFundsBusinessLogService maintenanceFundsBusinessLogService;
    @Autowired
    private IGwjMaintenanceFundsBusinessInfoService maintenanceFundsBusinessInfoService;
    @Autowired
    private IGwjMaintenanceFundsBusinessHouseService maintenanceFundsBusinessHouseService;
    @Autowired
    private IGwjMaintenanceFundsBusinessBuildService maintenanceFundsBusinessBuildService;
    @Autowired
    private IGwjMaintenanceFundsBusinessOwnerService maintenanceFundsBusinessOwnerService;
    @Autowired
    private MaintenanceFundsBusinessConfiguration maintenanceFundsBusinessConfiguration;
    @Autowired
    private IGwjMaintenanceFundsBusinessCommunityService maintenanceFundsBusinessCommunityService;
    @Autowired
    private IGwjMaintenanceFundsBusinessAttachmentService maintenanceFundsBusinessAttachmentService;
    @Autowired
    private MqSendMessageHandler mqSendMessageHandler;
    @Autowired
    private RemoteGwjConfigService remoteGwjConfigService;
    @Autowired
    private RemoteGwjFinanceService remoteGwjFinanceService;
    @Autowired
    private IGwjBaseHouseService baseHouseService;

    @Autowired
    private RemoteGwjExpendService remoteGwjExpendService;

    /**
     * 查询公维金维修资金业务
     *
     * @param bizId 公维金维修资金业务主键
     * @return 公维金维修资金业务
     */
    @Override
    public GwjMaintenanceFundsBusinessGetInfoDTO getInfoDetails(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = getGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusinessRequest() {
            {
                setBizId(bizId);
            }
        });
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException("GwjMaintenanceFundsBusiness为空");
        }
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        List<GwjMaintenanceFundsBusinessBuild> maintenanceFundsBusinessBuildList = maintenanceFundsBusinessBuildService.selectGwjMaintenanceFundsBusinessBuildList(new GwjMaintenanceFundsBusinessBuild() {
            {
                setBizId(bizId);
            }
        });
        GwjMaintenanceFundsBusinessCommunity gwjMaintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(bizId);
        GwjMaintenanceFundsBusinessDTO maintenanceFundsBusinessDTO = BeanUtil.copyProperties(maintenanceFundsBusiness, GwjMaintenanceFundsBusinessDTO.class);
        try {
            R<GwjConfBusinessFlag> r = remoteGwjConfigService.selectGwjConfBusinessFlagByBizFlagId(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException(r.getMsg());
            }
            maintenanceFundsBusinessDTO.setCategory(r.getData().getCategory());
            maintenanceFundsBusinessDTO.setFlowName(r.getData().getSubcategory());
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常,异常信息: [{}]", e);
            throw new ServiceException("远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常");
        }
        maintenanceFundsBusinessDTO.setCommunityName(gwjMaintenanceFundsBusinessCommunity.getCommunityName());
        maintenanceFundsBusinessDTO.setOwnerCommitteeName(gwjMaintenanceFundsBusinessCommunity.getOwnerCommitteeName());
        maintenanceFundsBusinessDTO.setDevelopmentEnterpriseName(gwjMaintenanceFundsBusinessCommunity.getDevelopmentEnterpriseName());

        GwjMaintenanceFundsBusinessInfoDTO maintenanceFundsBusinessInfoDTO = BeanUtil.copyProperties(maintenanceFundsBusinessInfo, GwjMaintenanceFundsBusinessInfoDTO.class);
        List<GwjMaintenanceFundsBusinessBuildDTO> maintenanceFundsBusinessBuildLDTOList = BeanUtil.copyToList(maintenanceFundsBusinessBuildList, GwjMaintenanceFundsBusinessBuildDTO.class);
        return new GwjMaintenanceFundsBusinessGetInfoDTO() {
            {
                setMaintenanceFundsBusinessDTO(maintenanceFundsBusinessDTO);
                setMaintenanceFundsBusinessInfoDTO(maintenanceFundsBusinessInfoDTO);
                setMaintenanceFundsBusinessBuildDTOList(maintenanceFundsBusinessBuildLDTOList);
            }
        };
    }

    /**
     * 根据flowId查询业务流程
     *
     * @param flowId 业务流程主键
     * @return 业务流程
     */
    @Override
    public GwjConfFlow selectGwjConfFlowByFlowId(Long flowId) {
        return maintenanceFundsBusinessMapper.selectGwjConfFlowByFlowId(flowId);
    }

    /**
     * 查询公维金维修资金业务列表
     *
     * @param maintenanceFundsBusinessListRequest 公维金维修资金业务
     * @return 公维金维修资金业务
     */
    @Override
    public List<GwjMaintenanceFundsBusinessListDTO> getGwjMaintenanceFundsBusinessList(GwjMaintenanceFundsBusinessListRequest maintenanceFundsBusinessListRequest) {
        return maintenanceFundsBusinessMapper.getGwjMaintenanceFundsBusinessList(maintenanceFundsBusinessListRequest);
    }

    /**
     * 查询公维金维修资金业务列表
     *
     * @param gwjMaintenanceFundsBusiness 公维金维修资金业务
     * @return 公维金维修资金业务
     */
    @Override
    public List<GwjMaintenanceFundsBusiness> selectGwjMaintenanceFundsBusinessList(GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness) {
        return maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessList(gwjMaintenanceFundsBusiness);
    }

    /**
     * 新增公维金维修资金业务
     *
     * @param gwjMaintenanceFundsBusiness 公维金维修资金业务
     * @return 结果
     */
    // @CachePut(value = "gwj_intranet:maintenance_funds_business", key = "#gwjMaintenanceFundsBusiness.bizId", unless =
    // "#result == null")
    @Override
    public GwjMaintenanceFundsBusiness insertGwjMaintenanceFundsBusiness(GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness) {
        if (ObjectUtil.notEqual(maintenanceFundsBusinessMapper.insertGwjMaintenanceFundsBusiness(gwjMaintenanceFundsBusiness), FlagStatusEnum.SUC.getCode())) {
            return null;
        }
        return maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(gwjMaintenanceFundsBusiness.getBizId());
    }

    // @CachePut(value = "gwj_intranet:maintenance_funds_business", key = "#gwjMaintenanceFundsBusiness.bizId", unless =
    // "#result == null")
    @Override
    public GwjMaintenanceFundsBusiness updateGwjMaintenanceFundsBusiness(GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness) {
        gwjMaintenanceFundsBusiness.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
        gwjMaintenanceFundsBusiness.setUpdateTime(DateUtils.getNowDate());
        if (ObjectUtil.notEqual(maintenanceFundsBusinessMapper.updateGwjMaintenanceFundsBusiness(gwjMaintenanceFundsBusiness), FlagStatusEnum.SUC.getCode())) {
            return null;
        }
        return maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(gwjMaintenanceFundsBusiness.getBizId());
    }

    @ConfStepConfigCheck(bizId = "#businessProcessRequest.bizId", checkUser = FlagStatusEnum.FAL, stepConfigInfo = {StepConfigInfoEnum.TAKE_PARTS}, businessStatus = {BusinessStatusEnum.SUBMIT})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int takeParts(BusinessProcessRequest businessProcessRequest) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = getGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusinessRequest() {
            {
                setBizId(businessProcessRequest.getBizId());
            }
        });
        Optional.ofNullable(maintenanceFundsBusiness).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.TAKE_PARTS_FAL) + "GwjMaintenanceFundsBusiness为空");
        });
        Optional.ofNullable(((IGwjMaintenanceFundsBusinessService)AopContext.currentProxy()).updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                setAcceptTime(LocalDateTime.now());
                setBizId(businessProcessRequest.getBizId());
                setStatus(BusinessStatusEnum.TAKE_PARTS.getCode());
                setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
                setCurrentOperId(SecurityUtils.getLoginUser().getUserid());
                setCurrentOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.TAKE_PARTS_FAL) + "GwjMaintenanceFundsBusiness更新失败");
        });
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
                setContent(businessProcessRequest.getContent());
                setResult(GwjBusinessLogResult.TAKE_PARTS.getCode());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.TAKE_PARTS_FAL) + "签署意见GwjMaintenanceFundsBusinessLog新增失败");
        }
        return FlagStatusEnum.SUC.getCode();
    }

    @Override
    public AllocatedAmountSelectDTO allocatedAmountSelect(AllocatedAmountRequest allocatedAmountRequest) {
        List<AllocatedAmountListDTO> maintenanceFundsBusinessHouseList = maintenanceFundsBusinessHouseService.allocatedAmountList(allocatedAmountRequest);
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessHouseList)) {
            return null;
        }
        // 别再改回去了，这个查询是要统计用的
        List<AllocatedAmountListDTO> maintenanceFundsBusinessHouseList1 = maintenanceFundsBusinessHouseService.allocatedAmountList(allocatedAmountRequest);
        // List<AllocatedAmountListDTO> maintenanceFundsBusinessHouseList1 = new ArrayList<AllocatedAmountListDTO>();
        // maintenanceFundsBusinessHouseList1.addAll(maintenanceFundsBusinessHouseList);
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(allocatedAmountRequest.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessInfo)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.ALLOCATED_AMOUNT_SELECT) + "维修资金使用申请工程信息GwjMaintenanceFundsBusinessInfo不能为空");
        }
        List<String> useTypeList = maintenanceFundsBusinessHouseService.selectUseTypeList();
        if (CollectionUtil.isEmpty(useTypeList)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.ALLOCATED_AMOUNT_SELECT) + "未获取到对应的房屋用途列表");
        }
        BigDecimal selfRaiseMoney = maintenanceFundsBusinessHouseList1.stream().map(AllocatedAmountListDTO::getSelfRaiseMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalAllocationMoney = maintenanceFundsBusinessHouseList1.stream().map(AllocatedAmountListDTO::getTotalAllocationMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal actualAllocationMoney = maintenanceFundsBusinessHouseList1.stream().map(AllocatedAmountListDTO::getActualAllocationMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        return new AllocatedAmountSelectDTO() {
            {
                setSelfRaiseMoney(selfRaiseMoney);
                setTotalAllocationMoney(totalAllocationMoney);
                setActualAllocationMoney(actualAllocationMoney);
                setTotalHouseholds(maintenanceFundsBusinessInfo.getTotalHouseholds());
                setTotalAreaInvolved(maintenanceFundsBusinessInfo.getTotalInvolvedArea());
                setProjectBudgetAmount(maintenanceFundsBusinessInfo.getProjectBudgetAmount());// 20230726 变更
                setTableDataInfo(PageUtils.getDataTable(maintenanceFundsBusinessHouseList));
                setUseTypeList(useTypeList);
                setTotalSettlementAmount(maintenanceFundsBusinessInfo.getTotalSettlementAmount() == null ? BigDecimal.ZERO : maintenanceFundsBusinessInfo.getTotalSettlementAmount());
            }
        };
    }

    @ConfStepConfigCheck(bizId = "#bizId", stepConfigInfo = {StepConfigInfoEnum.EXAMINE}, businessStatus = {BusinessStatusEnum.TAKE_PARTS})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public PreAcceptMessage preAcceptExamine(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException("GwjMaintenanceFundsBusiness为空");
        }

        GwjMaintenanceFundsBusiness maintenanceFundsBusiness1 = new GwjMaintenanceFundsBusiness();
        maintenanceFundsBusiness1.setBizId(maintenanceFundsBusiness.getBizId());
        maintenanceFundsBusiness1.setStatus(BusinessStatusEnum.APPROVED.getCode());
        maintenanceFundsBusiness1.setVoteFlag(FlagStatusEnum.SUC.getCode());
        switch (GwjBusinessFlagType.translate(maintenanceFundsBusiness.getBizFlagId())) {
            case EXPEND_PRE:
                maintenanceFundsBusiness1.setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
                break;
            case EXPEND_URGENT_PRE:
                maintenanceFundsBusiness1.setServerStatus(BusinessServerStatusEnum.FINISH.getCode());
                try {
                    R<GwjConfStep> r = remoteGwjConfigService.getFinalStep(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
                    if (R.isError(r)) {
                        throw new ServiceException(r.getMsg());
                    }
                    if (ObjectUtil.isNull(r.getData())) {
                        throw new ServiceException(r.getMsg());
                    }
                    maintenanceFundsBusiness1.setStepId(r.getData().getStepId());
                } catch (Exception e) {
                    log.error("远程调用 -> [remoteGwjConfigService][getFinalStep]异常,异常信息: [{}]", e);
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_EXAMINE) + "远程调用 -> [remoteGwjConfigService][getFinalStep]异常");
                }
                int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
                    {
                        setBizId(maintenanceFundsBusiness.getBizId());
                        setStepId(maintenanceFundsBusiness1.getStepId());
                        setResult(GwjBusinessLogResult.FINISH.getCode());
                        setAcceptTime(LocalDateTimeUtil.offset(LocalDateTime.now(), 1, ChronoUnit.SECONDS));
                    }
                });
                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
                    throw new ServiceException("GwjMaintenanceFundsBusinessLog新增失败");
                }
                break;
            default:
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_EXAMINE) + "GwjBusinessFlagType未获取到对应的业务标识类型");
        }
        Optional.ofNullable(((IGwjMaintenanceFundsBusinessService)AopContext.currentProxy()).updateGwjMaintenanceFundsBusiness(maintenanceFundsBusiness1)).<ServiceException>orElseThrow(() -> {
            throw new ServiceException("GwjMaintenanceFundsBusiness更新失败");
        });
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
                setResult(GwjBusinessLogResult.PASS.getCode());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException("GwjMaintenanceFundsBusinessLog新增失败");
        }
        PreAcceptMessage preAcceptMessage = new PreAcceptMessage() {
            {
                setAcceptTime(LocalDateTime.now());
                setOperId(maintenanceFundsBusiness.getCurrentOperId());
                setOperName(maintenanceFundsBusiness.getCurrentOperName());
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                setOutServerIdentification(maintenanceFundsBusiness.getOutServerIdentification());
            }
        };
        if (ObjectUtil.isEmpty(preAcceptMessage)) {
            throw new ServiceException("预受理审核步骤回调参数不能为空");
        }
        //
        // try {
        // // 同步公维金外网支出步骤为二次补件
        // remoteGwjExpendService.preAcceptExamine(JSONUtil.toJsonStr(preAcceptMessage), SecurityConstants.INNER);
        // } catch (Exception e) {
        // throw new ServiceException("预受理审核步骤同步失败");
        // }
        R<Boolean> result = remoteGwjExpendService.preAcceptExamine(JSONUtil.toJsonStr(preAcceptMessage), SecurityConstants.INNER);
        if (R.isError(result)) {
            throw new ServiceException("预受理审核步骤同步失败");
        }
        return preAcceptMessage;
    }

    @Override
    public GwjMaintenanceFundsBusiness getGwjMaintenanceFundsBusiness(GwjMaintenanceFundsBusinessRequest maintenanceFundsBusinessRequest) {
        return maintenanceFundsBusinessMapper.getGwjMaintenanceFundsBusiness(maintenanceFundsBusinessRequest);
    }

    @ConfStepConfigCheck(bizId = "#businessProcessRequest.bizId", stepConfigInfo = {StepConfigInfoEnum.RETREAT_PARTS}, businessStatus = {BusinessStatusEnum.SUBMIT, BusinessStatusEnum.TAKE_PARTS})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int preAcceptRetreat(BusinessProcessRequest businessProcessRequest) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(businessProcessRequest.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FIRST_ATTACHMENT_RETREAT) + "未获取到对应公共维修资金业务信息");
        }
        // 1.更新基础业务表
        Optional.ofNullable(((IGwjMaintenanceFundsBusinessService)AopContext.currentProxy()).updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
                setStatus(BusinessStatusEnum.RETREAT_PARTS.getCode());
                setServerStatus(BusinessServerStatusEnum.RETREAT_PARTS.getCode());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FIRST_ATTACHMENT_RETREAT) + "公共维修资金业务信息更新失败");
        });
        // 2.新增日志
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
                setContent(businessProcessRequest.getContent());
                setResult(GwjBusinessLogResult.RETREAT_PARTS.getCode());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FIRST_ATTACHMENT_RETREAT) + "GwjMaintenanceFundsBusinessLog签署意见新增失败");
        }

        PreAcceptMessage preAcceptMessage = new PreAcceptMessage();
        preAcceptMessage.setContent(businessProcessRequest.getContent());
        preAcceptMessage.setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
        preAcceptMessage.setOutServerIdentification(maintenanceFundsBusiness.getOutServerIdentification());
        preAcceptMessage.setOperId(SecurityUtils.getLoginUser().getUserid());
        preAcceptMessage.setOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
        preAcceptMessage.setAcceptTime(LocalDateTime.now());

        // 提交到外网
        String tag = maintenanceFundsBusinessConfiguration.tagProperties().getPreAcceptRetreat();
        MqSendResult mqSendResult = mqSendMessageHandler.syncSend(new MaintenanceFundsMqMessageBody() {
            {
                setJsonMsg(JSONUtil.toJsonStr(preAcceptMessage));
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        }, new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessSendRequest(tag, null));
        if (mqSendResult.isSuccess()) {
            return FlagStatusEnum.SUC.getCode();
        } else {
            log.error("公维金资金申请提交数据到内网MQ异常 -> [{}]", mqSendResult.getMessage());
            // throw new ServiceException(MaintenanceFundsErrorEnum.FIRST_ATTACHMENT_RETREAT, "公维金资金申请提交数据到内网MQ异常");
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FIRST_ATTACHMENT_RETREAT) + "公维金资金申请提交失败，请查看网络是否正常！");
        }
    }

    /**
     * 查询公维金维修资金业务
     *
     * @param bizId 公维金维修资金业务主键
     * @return 公维金维修资金业务
     */
    // @Cacheable(value = "gwj_intranet:maintenance_funds_business", key = "#bizId", unless = "#result == null")
    @Override
    public GwjMaintenanceFundsBusiness selectGwjMaintenanceFundsBusinessByBusinessId(Long bizId) {
        return maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
    }

    @ConfStepConfigCheck(bizId = "#bizId", stepConfigInfo = {StepConfigInfoEnum.EXAMINE}, businessStatus = {BusinessStatusEnum.SUBMIT})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int preAcceptSecondExamine(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.getGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusinessRequest() {
            {
                setBizId(bizId);
            }
        });
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "未获取到对应公共维修资金业务");
        }
        long stepId;
        try {
            R<GwjConfStep> r = remoteGwjConfigService.getFinalStep(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException(r.getMsg());
            }
            stepId = r.getData().getStepId();
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][getFinalStep]异常,异常信息: [{}]", e);
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_EXAMINE) + "远程调用 -> [remoteGwjConfigService][getFinalStep]异常");
        }
        Optional.ofNullable(((IGwjMaintenanceFundsBusinessService)AopContext.currentProxy()).updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                setStepId(stepId);
                setBizId(maintenanceFundsBusiness.getBizId());
                setStatus(BusinessStatusEnum.APPROVED.getCode());
                setServerStatus(BusinessServerStatusEnum.FINISH.getCode());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "公共维修资金业务更新失败");
        });
        List<GwjMaintenanceFundsBusinessHouse> maintenanceFundsBusinessHouseList = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setBizId(bizId);
            }
        });
        List<GwjMaintenanceFundsBusinessBuild> maintenanceFundsBusinessBuildList = maintenanceFundsBusinessBuildService.selectGwjMaintenanceFundsBusinessBuildList(new GwjMaintenanceFundsBusinessBuild() {
            {
                setBizId(bizId);
            }
        });
        List<GwjMaintenanceFundsBusinessOwner> maintenanceFundsBusinessOwnerList = maintenanceFundsBusinessOwnerService.selectGwjMaintenanceFundsBusinessOwnerList(new GwjMaintenanceFundsBusinessOwner() {
            {
                setBizId(bizId);
            }
        });
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(bizId);
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        List<GwjMaintenanceFundsBusinessAttachment> attachmentList = maintenanceFundsBusinessAttachmentService.selectGwjMaintenanceFundsBusinessAttachmentList(new GwjMaintenanceFundsBusinessAttachment() {
            {
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        });

        PreAcceptSecondExamineInnerMessage preAcceptSecondExamineInnerMessage = new PreAcceptSecondExamineInnerMessage() {
            {
                setMaintenanceFundsBusiness(maintenanceFundsBusiness);
                setMaintenanceFundsBusinessAttachmentList(attachmentList);
                setMaintenanceFundsBusinessInfo(maintenanceFundsBusinessInfo);
                setMaintenanceFundsBusinessCommunity(maintenanceFundsBusinessCommunity);
                setMaintenanceFundsBusinessBuildList(maintenanceFundsBusinessBuildList);
                setMaintenanceFundsBusinessHouseList(maintenanceFundsBusinessHouseList);
                setMaintenanceFundsBusinessOwnerList(maintenanceFundsBusinessOwnerList);
            }
        };
        if (ObjectUtil.equal(insertFormal(preAcceptSecondExamineInnerMessage), FlagStatusEnum.FAL.getCode())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "二次补件审核MQ消息发送异常");
        }
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
                setResult(GwjBusinessLogResult.PASS.getCode());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "签署意见GwjMaintenanceFundsBusinessLog新增失败");
        }
        insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setStepId(stepId);
                setBizId(maintenanceFundsBusiness.getBizId());
                setResult(GwjBusinessLogResult.FINISH.getCode());
                setAcceptTime(LocalDateTimeUtil.offset(LocalDateTime.now(), 1, ChronoUnit.SECONDS));
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "签署意见GwjMaintenanceFundsBusinessLog新增失败");
        }
        PreAcceptMessage preAcceptMessage = new PreAcceptMessage() {
            {
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                setOutServerIdentification(maintenanceFundsBusiness.getOutServerIdentification());
                setAcceptTime(maintenanceFundsBusiness.getAcceptTime());
                setOperId(SecurityUtils.getLoginUser().getUserid());
                setOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
            }
        };
        String tag = maintenanceFundsBusinessConfiguration.tagProperties().getPreAcceptSecondExamine();
        MqSendResult mqSendResult = mqSendMessageHandler.syncSend(new MaintenanceFundsMqMessageBody() {
            {
                setJsonMsg(JSONUtil.toJsonStr(preAcceptMessage));
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        }, new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessSendRequest(tag, null));
        if (mqSendResult.isSuccess()) {
            return FlagStatusEnum.SUC.getCode();
        } else {
            log.error("二次补件审核MQ消息发送异常 -> [{}]", mqSendResult.getMessage());
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "二次补件审核MQ消息发送异常");
        }
    }

    public int insertFormal(PreAcceptSecondExamineInnerMessage preAcceptSecondExamineInnerMessage) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = BeanUtil.copyProperties(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusiness(), GwjMaintenanceFundsBusiness.class);
        maintenanceFundsBusiness.setBizFlagId(GwjBusinessFlagType.EXPEND_FORMAL.getCode());
        try {
            R<GwjConfStep> r = remoteGwjConfigService.getFirstStep(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException(r.getMsg());
            }
            maintenanceFundsBusiness.setStepId(r.getData().getStepId());
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]异常,异常信息: [{}]", e);
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "远程调用 -> [remoteGwjConfigService][getFirstStep]异常");
        }
        try {
            R<GwjConfBusinessFlag> r = remoteGwjConfigService.selectGwjConfBusinessFlagByBizFlagId(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException("远程调用获取配置失败");
            }
            maintenanceFundsBusiness.setFlowId(r.getData().getFlowId());
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常,异常信息: [{}]", e);
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "远程调用 -> [remoteGwjConfigService][selectGwjConfBusinessFlagByBizFlagId]异常");
        }
        maintenanceFundsBusiness.setBizId(null);
        maintenanceFundsBusiness.setStatus(BusinessStatusEnum.SUBMIT.getCode());
        maintenanceFundsBusiness.setCurrentOperName(null);
        maintenanceFundsBusiness.setCurrentOperId(null);
        maintenanceFundsBusiness.setType(BusinessTypeEnum.FORMAL.getCode());
        maintenanceFundsBusiness.setServerIdentification(IdUtil.getSnowflakeNextIdStr());
        maintenanceFundsBusiness.setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
        maintenanceFundsBusiness.setOutServerIdentification(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusiness().getServerIdentification());
        Optional.ofNullable(insertGwjMaintenanceFundsBusiness(maintenanceFundsBusiness)).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "公共维修资金业务GwjMaintenanceFundsBusiness更新失败");
        });
        preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessBuildList().forEach(build -> {
            build.setBizId(maintenanceFundsBusiness.getBizId());
        });
        if (ObjectUtil.equal(maintenanceFundsBusinessBuildService.insertBatchGwjMaintenanceFundsBusinessBuild(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessBuildList()), FlagStatusEnum.FAL.getCode())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "GwjMaintenanceFundsBusinessBuild新增业务楼栋失败");
        }
        preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessCommunity().setBizId(maintenanceFundsBusiness.getBizId());
        Optional.ofNullable(maintenanceFundsBusinessCommunityService.insertGwjMaintenanceFundsBusinessCommunity(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessCommunity())).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "GwjMaintenanceFundsBusinessCommunity新增业务项目失败");
        });
        preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessHouseList().forEach(house -> {
            house.setBizId(maintenanceFundsBusiness.getBizId());
        });
        if (ObjectUtil.equal(maintenanceFundsBusinessHouseService.insertBatchGwjMaintenanceFundsBusinessHouse(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessHouseList()), FlagStatusEnum.FAL.getCode())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "GwjMaintenanceFundsBusinessHouse新增业务房屋失败");
        }
        preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessInfo().setBizId(maintenanceFundsBusiness.getBizId());
        Optional.ofNullable(maintenanceFundsBusinessInfoService.insertGwjMaintenanceFundsBusinessInfo(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessInfo())).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "维修资金使用申请工程信息GwjMaintenanceFundsBusinessInfo新增失败");
        });
        preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessOwnerList().forEach(owner -> {
            owner.setBizId(maintenanceFundsBusiness.getBizId());
        });
        if (ObjectUtil.equal(maintenanceFundsBusinessOwnerService.insertBatchGwjMaintenanceFundsBusinessOwner(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessOwnerList()), FlagStatusEnum.FAL.getCode())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "GwjMaintenanceFundsBusinessOwner新增失败");
        }
        preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessAttachmentList().forEach(file -> {
            file.setReceiveFlag(FlagStatusEnum.FAL.getCode());
            file.setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
        });
        if (ObjectUtil.equal(maintenanceFundsBusinessAttachmentService.insertBatchAttachment(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusinessAttachmentList()), FlagStatusEnum.FAL.getCode())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "GwjBaseFile新增失败");
        }
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setResult(GwjBusinessLogResult.SUBMIT.getCode());
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
                setOperId(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusiness().getCurrentOperId());
                setOperName(preAcceptSecondExamineInnerMessage.getMaintenanceFundsBusiness().getCurrentOperName());
            }
        });
        if (ObjectUtil.equal(insertFlag, FlagStatusEnum.FAL.getCode())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.PRE_ACCEPT_SECOND_EXAMINE) + "GwjMaintenanceFundsBusinessLog新增失败");
        }
        return insertFlag;
    }

    @Override
    public StepConfigInfoDTO getStepConfigInfo(GwjBusinessFlagType... businessFlagTypes) {
        StepConfigInfoDTO stepConfigInfoDTO = new StepConfigInfoDTO();
        List<GwjConfStepDTO> confStepDTOList = ListUtil.toList();
        List<GwjConfStepDTO> finalConfStepDTOList = confStepDTOList;
        Arrays.stream(businessFlagTypes).forEach(flag -> {
            try {
                R<List<GwjConfStep>> r = remoteGwjConfigService.selectGwjConfStepListByFlagId(flag.getCode(), SecurityConstants.INNER);
                if (R.isError(r)) {
                    throw new ServiceException(r.getMsg());
                }
                if (ObjectUtil.isNull(r.getData()) || CollectionUtil.isEmpty(r.getData())) {
                    throw new ServiceException("数据为空");
                }
                finalConfStepDTOList.addAll(BeanUtil.copyToList(r.getData(), GwjConfStepDTO.class));
            } catch (Exception e) {
                log.error("远程调用 -> [remoteGwjConfigService][selectGwjConfStepListByFlagId]异常,异常信息: [{}]", e);
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_BUSINESS_STEP_CONFIG_INFO) + "远程调用 -> [remoteGwjConfigService][selectGwjConfStepListByFlagId]异常");
            }
        });
        confStepDTOList = finalConfStepDTOList.stream().distinct().collect(Collectors.toList());
        stepConfigInfoDTO.setConfStepList(confStepDTOList);
        confStepDTOList.forEach(step -> {
            List<String> configs = remoteGwjConfigService.selectGwjConfStepConfigInfoCodeListByBizFlagId(step.getStepId(), SecurityConstants.INNER).getData();
            step.setConfigList(configs);
        });
        return stepConfigInfoDTO;
    }

    @Override
    public List<GwjMaintenanceFundsBusinessHouse> allocatedAmountCancelList(AllocatedAmountRequest allocatedAmountRequest) {
        return maintenanceFundsBusinessHouseService.selectCancelHouseList(allocatedAmountRequest);
    }

    @Override
    public ApplicationReportDTO getApplicationReport(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_APPLICATION_REPORT) + "未获取到对应的公共维修资金业务");
        }
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(maintenanceFundsBusiness.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessCommunity)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_APPLICATION_REPORT) + "未获取到对应业务小区信息");
        }
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        if (ObjectUtil.isNull(maintenanceFundsBusinessInfo)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_APPLICATION_REPORT) + "未获取到对应维修资金使用申请工程信息");
        }
        GwjMaintenanceFundsBusinessAttachment maintenanceFundsBusinessAttachment = maintenanceFundsBusinessAttachmentService.getGwjMaintenanceFundsBusinessAttachment(new GwjMaintenanceFundsBusinessAttachment() {
            {
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                setServerType(BusinessAttachmentServerTypeEnum.APPLICATION_REPORT.getCode());
                setType(BusinessAttachmentTypeEnum.REPORT.getCode());
            }
        });
        return new ApplicationReportDTO() {
            {
                setAddress(maintenanceFundsBusiness.getAddress());
                setApplyName(maintenanceFundsBusiness.getApplicantUserName());
                setCommunityName(maintenanceFundsBusinessCommunity.getCommunityName());
                setDevelopmentEnterpriseName(maintenanceFundsBusinessCommunity.getDevelopmentEnterpriseName());
                setCompletedTime(maintenanceFundsBusiness.getCompletedTime());
                setTotalBuild(maintenanceFundsBusinessCommunity.getTotalBuild());
                setTotalSize(maintenanceFundsBusinessCommunity.getTotalSize());
                setTotalOwner(maintenanceFundsBusinessCommunity.getTotalOwner());
                setMaintenanceItems(maintenanceFundsBusinessInfo.getMaintenanceItems());
                setMaintenanceReason(maintenanceFundsBusinessInfo.getMaintenanceReason());
                setProjectBudgetAmount(maintenanceFundsBusinessInfo.getProjectBudgetAmount());
                setApplicationUnitName(maintenanceFundsBusinessInfo.getApplicationUnitName());
                if (ObjectUtil.isNotNull(maintenanceFundsBusinessAttachment)) {
                    setAttachmentId(maintenanceFundsBusinessAttachment.getAttachmentId());
                    ApplicationReportRequest applicationReport = JSONUtil.toBean(maintenanceFundsBusinessAttachment.getContent(), ApplicationReportRequest.class);
                    setCompletionTime(applicationReport.getCompletionTime());
                    setPublicityStartTime(applicationReport.getPublicityStartTime());
                    setPublicityEndTime(applicationReport.getPublicityEndTime());
                    setPositionInformation(applicationReport.getPositionInformation());
                    setSignTime(applicationReport.getSignTime());
                    setExploredOwnerNumber(applicationReport.getExploredOwnerNumber());
                }
            }
        };
    }

    @Override
    public Optional<GwjMaintenanceFundsBusiness> delete4Save(Function<Long, Optional<PreAcceptSubmitMessage>> businessDelete2SaveRequest, Long bizId, BusinessModuleTypeEnum... deleteModuleTypeEnums) {
        Optional<PreAcceptSubmitMessage> optional = businessDelete2SaveRequest.apply(bizId);
        try {
            AtomicReference<GwjMaintenanceFundsBusiness> maintenanceFundsBusiness = new AtomicReference<>();
            optional.ifPresent((request) -> {
                String serverIdentification = request.getMaintenanceFundsBusiness().getServerIdentification();
                maintenanceFundsBusiness.set(insertGwjMaintenanceFundsBusiness(request.getMaintenanceFundsBusiness()));
                if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
                    throw new ServiceException("GwjMaintenanceFundsBusiness插入/更新失败");
                }
                if (ObjectUtil.isNotNull(deleteModuleTypeEnums)) {
                    Arrays.stream(deleteModuleTypeEnums).forEach(businessModuleTypeEnum -> {
                        int deleteFlag = FlagStatusEnum.FAL.getCode();
                        switch (businessModuleTypeEnum) {
                            case INFO:
                                deleteFlag = maintenanceFundsBusinessInfoService.deleteGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
                                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), deleteFlag)) {

                                }
                                break;
                            case COMMUNITY:
                                deleteFlag = maintenanceFundsBusinessCommunityService.deleteGwjMaintenanceFundsBusinessCommunityByBusinessId(bizId);
                                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), deleteFlag)) {

                                }
                                break;
                            case BUILD:
                                deleteFlag = maintenanceFundsBusinessBuildService.deleteGwjMaintenanceFundsBusinessBuildByBusinessId(bizId);
                                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), deleteFlag)) {

                                }
                                break;
                            case HOUSE:
                                deleteFlag = maintenanceFundsBusinessHouseService.deleteGwjMaintenanceFundsBusinessHouseByBusinessId(bizId);
                                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), deleteFlag)) {

                                }
                                break;
                            case OWNER:
                                deleteFlag = maintenanceFundsBusinessOwnerService.deleteGwjMaintenanceFundsBusinessOwnerByBusinessId(bizId);
                                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), deleteFlag)) {

                                }
                                break;
                            case ATTACHMENT:
                                deleteFlag = maintenanceFundsBusinessAttachmentService.deleteGwjMaintenanceFundsBusinessAttachmentByServerIdentification(serverIdentification);
                                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), deleteFlag)) {

                                }
                                break;
                        }
                    });
                }
                int insertFlag = FlagStatusEnum.FAL.getCode();
                request.getMaintenanceFundsBusinessInfo().setBizId(maintenanceFundsBusiness.get().getBizId());
                GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.insertGwjMaintenanceFundsBusinessInfo(request.getMaintenanceFundsBusinessInfo());
                if (ObjectUtil.isNull(maintenanceFundsBusinessInfo)) {
                    throw new ServiceException("GwjMaintenanceFundsBusinessInfo插入失败");
                }
                request.getMaintenanceFundsBusinessCommunity().setBizId(maintenanceFundsBusiness.get().getBizId());
                GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.insertGwjMaintenanceFundsBusinessCommunity(request.getMaintenanceFundsBusinessCommunity());
                if (ObjectUtil.isNull(maintenanceFundsBusinessCommunity)) {
                    throw new ServiceException("GwjMaintenanceFundsBusinessCommunity插入失败");
                }
                request.getMaintenanceFundsBusinessBuildList().forEach(build -> build.setBizId(maintenanceFundsBusiness.get().getBizId()));
                insertFlag = maintenanceFundsBusinessBuildService.insertBatchGwjMaintenanceFundsBusinessBuild(request.getMaintenanceFundsBusinessBuildList());
                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
                    throw new ServiceException("List<GwjMaintenanceFundsBusinessBuild>插入失败");
                }
                request.getMaintenanceFundsBusinessHouseList().forEach(build -> build.setBizId(maintenanceFundsBusiness.get().getBizId()));
                insertFlag = maintenanceFundsBusinessHouseService.insertBatchGwjMaintenanceFundsBusinessHouse(request.getMaintenanceFundsBusinessHouseList());
                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
                    throw new ServiceException("List<GwjMaintenanceFundsBusinessHouse>插入失败");
                }
                request.getMaintenanceFundsBusinessOwnerList().forEach(build -> build.setBizId(maintenanceFundsBusiness.get().getBizId()));
                insertFlag = maintenanceFundsBusinessOwnerService.insertBatchGwjMaintenanceFundsBusinessOwner(request.getMaintenanceFundsBusinessOwnerList());
                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
                    throw new ServiceException("List<GwjMaintenanceFundsBusinessOwner>插入失败");
                }
                request.getMaintenanceFundsBusinessAttachmentList().forEach(build -> build.setServerIdentification(maintenanceFundsBusiness.get().getServerIdentification()));
                insertFlag = maintenanceFundsBusinessAttachmentService.insertBatchAttachment(request.getMaintenanceFundsBusinessAttachmentList());
                if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
                    throw new ServiceException("List<GwjMaintenanceFundsBusinessAttachment>插入失败");
                }
            });
            return Optional.ofNullable(maintenanceFundsBusiness.get());
        } catch (Exception e) {
            log.error("delete4Save -> [{}]", e);
            return Optional.ofNullable(null);
        }
    }

    /**
     * 获取改造方案
     *
     * @param bizId 业务标识
     * @return {@link ChangeSchemeDTO}
     */
    @Override
    public ChangeSchemeDTO getTransformationPlan(Long bizId) {
        GwjMaintenanceFundsBusinessCommunity gwjMaintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(bizId);
        if (ObjectUtil.isNull(gwjMaintenanceFundsBusinessCommunity)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_TRANSFORMATION_PLAN) + "未获取到对应的业务小区信息");
        }
        GwjMaintenanceFundsBusinessInfo gwjMaintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        if (ObjectUtil.isNull(gwjMaintenanceFundsBusinessInfo)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_TRANSFORMATION_PLAN) + "未获取到对应维修资金使用申请工程信息");
        }
        GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness = selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        if (ObjectUtil.isNull(gwjMaintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_TRANSFORMATION_PLAN) + "未获取到公共维修资金业务信息");
        }
        GwjMaintenanceFundsBusinessAttachment maintenanceFundsBusinessAttachment = maintenanceFundsBusinessAttachmentService.getGwjMaintenanceFundsBusinessAttachment(new GwjMaintenanceFundsBusinessAttachment() {
            {
                setServerIdentification(gwjMaintenanceFundsBusiness.getServerIdentification());
                setServerType(BusinessAttachmentServerTypeEnum.TRANSFORMATION_PLAN.getCode());
                setType(BusinessAttachmentTypeEnum.REPORT.getCode());
            }
        });
        List<GwjMaintenanceFundsBusinessBuild> gwjMaintenanceFundsBusinessBuilds = maintenanceFundsBusinessBuildService.selectGwjMaintenanceFundsBusinessBuildList(new GwjMaintenanceFundsBusinessBuild() {
            {
                setBizId(bizId);
            }
        });
        StringBuffer buildNameString = new StringBuffer();
        gwjMaintenanceFundsBusinessBuilds.forEach(build -> buildNameString.append(build.getBuildName().concat("，")));
        buildNameString.deleteCharAt(buildNameString.length() - 1);
        return new ChangeSchemeDTO() {
            {
                setCompletedTimeYear(DateUtil.year(gwjMaintenanceFundsBusiness.getCompletedTime()));
                setCompletedTimeMouth(DateUtil.month(gwjMaintenanceFundsBusiness.getCompletedTime()) + 1);
                setCommunityName(gwjMaintenanceFundsBusinessCommunity.getCommunityName());
                setDevelopmentEnterpriseName(gwjMaintenanceFundsBusinessCommunity.getDevelopmentEnterpriseName());
                setCommunityLocation(gwjMaintenanceFundsBusinessCommunity.getCommunityLocation());
                setTotalSize(gwjMaintenanceFundsBusinessCommunity.getTotalSize());
                setTotalOwner(gwjMaintenanceFundsBusinessCommunity.getTotalOwner());
                setTotalBuild(gwjMaintenanceFundsBusinessCommunity.getTotalBuild());
                setMaintenanceItems(gwjMaintenanceFundsBusinessInfo.getMaintenanceItems());
                setMaintenanceReason(gwjMaintenanceFundsBusinessInfo.getMaintenanceReason());
                setConstructionUnit(gwjMaintenanceFundsBusinessInfo.getConstructionUnit());
                setProjectBudgetAmount(gwjMaintenanceFundsBusinessInfo.getProjectBudgetAmount());
                setFullNameOfPayee(gwjMaintenanceFundsBusinessInfo.getPayeeName());
                setBankDeposit(gwjMaintenanceFundsBusinessInfo.getBankDeposit());
                setCollectionAccount(gwjMaintenanceFundsBusinessInfo.getCollectionAccount());
                setAcceptancePlan(gwjMaintenanceFundsBusinessInfo.getAcceptancePlan());
                setFullNameOfApplicationUnit(gwjMaintenanceFundsBusinessInfo.getApplicationUnitName());
                setBuildNameList(buildNameString.toString());
                if (ObjectUtil.isNotNull(maintenanceFundsBusinessAttachment)) {
                    setAttachmentId(maintenanceFundsBusinessAttachment.getAttachmentId());
                    GwjSaveChangeSchemeRequest gwjSaveChangeSchemeRequest = JSONUtil.toBean(maintenanceFundsBusinessAttachment.getContent(), GwjSaveChangeSchemeRequest.class);
                    setCostDetail(gwjSaveChangeSchemeRequest.getCostDetail());
                    setCorporateAccount(gwjSaveChangeSchemeRequest.getCorporateAccount());
                    setUpdateDetail(gwjSaveChangeSchemeRequest.getUpdateDetail());
                    setSaveTime(gwjSaveChangeSchemeRequest.getSaveTime());
                }
            }
        };
    }

    @ConfStepConfigCheck(bizId = "#submitRequest.bizId", checkUser = FlagStatusEnum.FAL, stepConfigInfo = {StepConfigInfoEnum.CONFIRM_ACCEPTANCE}, businessStatus = {BusinessStatusEnum.SUBMIT})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int confirmAcceptance(SubmitRequest submitRequest) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(submitRequest.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) + "未获取到公共维修资金业务");
        }
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setResult(GwjBusinessLogResult.TAKE_PARTS.getCode());
                setContent(submitRequest.getContent());
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) + "签署意见新增失败");
        }
        String tag = null;
        String archiveNum = null;
        MqSendRequest mqSendRequest = null;
        switch (GwjBusinessFlagType.translate(maintenanceFundsBusiness.getBizFlagId())) {
            case EXPEND_FORMAL:
                tag = maintenanceFundsBusinessConfiguration.tagProperties().getResultNotify();
                mqSendRequest = new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessSendRequest(tag, null);
            case EXPEND_URGENT_FORMAL:
                tag = maintenanceFundsBusinessConfiguration.urgentTagProperties().getResultNotify();
                mqSendRequest = new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessUrgentSendRequest(tag, null);
                if (StrUtil.isBlank(submitRequest.getAreaName())) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) + "地区名称areaName不能为空");
                }
                archiveNum = BaseArchiveNumServiceHandler.getInstance().getArchiveNumName(new BaseArchiveNumServiceHandler.ArchiveNum() {
                    {
                        setAreaName(submitRequest.getAreaName());
                        setAreaId(maintenanceFundsBusiness.getAreaId());
                        setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                    }
                });
                break;
            case EXPEND_APPROPRIATE_FORMAL:
                tag = maintenanceFundsBusinessConfiguration.appropriateTagProperties().getResultNotify();
                mqSendRequest = new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessAppropriateSendRequest(tag, null);
                break;
            case EXPEND_URGENT_APPROPRIATE_FORMAL:
                tag = maintenanceFundsBusinessConfiguration.urgentAppropriateTagProperties().getResultNotify();
                mqSendRequest = new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessUrgentAppropriateSendRequest(tag, null);
                break;
        }
        String finalArchiveNum = archiveNum;
        int updateFlag = maintenanceFundsBusinessMapper.updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                if (StrUtil.isNotBlank(finalArchiveNum)) {
                    setArchiveNum(finalArchiveNum);
                }
                setAcceptTime(LocalDateTime.now());
                setCurrentOperId(SecurityUtils.getLoginUser().getUserid());
                setCurrentOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
                setBizId(submitRequest.getBizId());
                setStatus(BusinessStatusEnum.TAKE_PARTS.getCode());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), updateFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) + "公共维修资金业务GwjMaintenanceFundsBusiness更新失败");
        }
        PreAcceptMessage preAcceptMessage = new PreAcceptMessage();
        preAcceptMessage.setAcceptTime(LocalDateTime.now());
        preAcceptMessage.setStepId(maintenanceFundsBusiness.getStepId());
        preAcceptMessage.setOperId(SecurityUtils.getLoginUser().getUserid());
        preAcceptMessage.setOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
        preAcceptMessage.setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
        preAcceptMessage.setOutServerIdentification(maintenanceFundsBusiness.getOutServerIdentification());

        // 步骤回调修改为远程调用
        // try {
        // remoteGwjExpendService.resultNotify(JSONUtil.toJsonStr(preAcceptMessage), SecurityConstants.INNER).getData();
        // } catch (Exception e) {
        // throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
        // "支出外网步骤回调异常:" + e.getMessage());
        // }
        R<Boolean> result = remoteGwjExpendService.resultNotify(JSONUtil.toJsonStr(preAcceptMessage), SecurityConstants.INNER);
        if (R.isError(result)) {
            throw new ServiceException("确认受理处理失败！支出外网步骤回调异常1:" + result.getMsg());
        }
        if (!result.getData()) {
            throw new ServiceException("确认受理处理失败！支出外网步骤回调异常2:" + result.getMsg());
        }
        return FlagStatusEnum.SUC.getCode();
    }

    @ConfStepConfigCheck(bizId = "#submitRequest.bizId", stepConfigInfo = {StepConfigInfoEnum.SUBMIT})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int submit(SubmitRequest submitRequest) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(submitRequest.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "未获取到公共维修资金业务信息");
        }
        if (ObjectUtil.notEqual(maintenanceFundsBusiness.getStatus(), submitRequest.getStatus())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "业务状态不一致,请重新提交");
        }
        BusinessStatusEnum statusEnum;
        BusinessStatusEnum oldStatusEnum = BusinessStatusEnum.transfer(submitRequest.getStatus());
        // 是否跳过步骤
        Boolean skipFlag = Boolean.FALSE;
        // 跳过后上一步步骤主键
        Long previousStepId = null;
        switch (oldStatusEnum) {
            // 1.受理阶段需要确认是否收件
            case TAKE_PARTS:
                try {
                    if (ObjectUtil.equal(BusinessTypeEnum.FORMAL.getCode(), maintenanceFundsBusiness.getType())) {
                        List<BusinessAttachmentServerTypeEnum> noServerTypeEnum = maintenanceFundsBusinessAttachmentService.checkNull(() -> {
                            List<GwjMaintenanceFundsBusinessAttachment> maintenanceFundsBusinessAttachmentList = maintenanceFundsBusinessAttachmentService.selectGwjMaintenanceFundsBusinessAttachmentList(new GwjMaintenanceFundsBusinessAttachment() {
                                {
                                    setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                                }
                            });
                            return Optional.of(maintenanceFundsBusinessAttachmentList);
                        }, true, BusinessAttachmentServerTypeEnum.getServerTypeList());
                        if (CollectionUtil.isNotEmpty(noServerTypeEnum)) {
                            throw new ServiceException("附件" + noServerTypeEnum.get(0).getInfo() + "未收件,请先确认收件");
                        }
                    }
                    if (ObjectUtil.equal(BusinessTypeEnum.URGENT_FORMAL.getCode(), maintenanceFundsBusiness.getType())) {
                        List<BusinessAttachmentServerTypeEnum> noServerTypeEnum = maintenanceFundsBusinessAttachmentService.checkNull(() -> {
                            List<GwjMaintenanceFundsBusinessAttachment> maintenanceFundsBusinessAttachmentList = maintenanceFundsBusinessAttachmentService.selectGwjMaintenanceFundsBusinessAttachmentList(new GwjMaintenanceFundsBusinessAttachment() {
                                {
                                    setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                                }
                            });
                            return Optional.of(maintenanceFundsBusinessAttachmentList);
                        }, true, BusinessAttachmentServerTypeEnum.getUrgentServerTypeList());
                        if (CollectionUtil.isNotEmpty(noServerTypeEnum)) {
                            throw new ServiceException("附件" + noServerTypeEnum.get(0).getInfo() + "未收件,请先确认收件");
                        }
                    }
                } catch (Exception e) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + e.getMessage());
                }
                statusEnum = BusinessStatusEnum.FIRST_INSTANCE;
                // ---------------------------20230901取消步骤回调 s--------------------------------------
                // 发送外网步骤回调
                // String takePartsJsonMsg = resultNotify(maintenanceFundsBusiness);
                // if (ObjectUtil.isEmpty(takePartsJsonMsg)) {
                // throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                // }
                // // 步骤回调修改为远程调用
                // try {
                // remoteGwjExpendService.resultNotify(takePartsJsonMsg, SecurityConstants.INNER).getData();
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // ---------------------------20230901取消步骤回调 e--------------------------------------
                break;
            // 2.初审提交阶段
            case FIRST_INSTANCE:
                statusEnum = BusinessStatusEnum.REEXAMINE;
                // ---------------------------20230901取消步骤回调 s--------------------------------------
                // 发送外网步骤回调
                // String firstInstanceJsonMsg = resultNotify(maintenanceFundsBusiness);
                // if (ObjectUtil.isEmpty(firstInstanceJsonMsg)) {
                // throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                // }
                // // 步骤回调修改为远程调用
                // try {
                // remoteGwjExpendService.resultNotify(firstInstanceJsonMsg, SecurityConstants.INNER).getData();
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // ---------------------------20230901取消步骤回调 e--------------------------------------
                break;
            // 3.复审提交阶段
            case REEXAMINE:
                GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(maintenanceFundsBusiness.getBizId());
                if (ObjectUtil.equal(AppropriationWayEnum.TWO.getCode(), maintenanceFundsBusinessInfo.getAppropriationWay())) {
                    if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), maintenanceFundsBusiness.getFinancialJournalFlag())) {
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "请先生成财务流水");
                    }
                    statusEnum = BusinessStatusEnum.FINANCE_CHECK;
                } else {
                    statusEnum = BusinessStatusEnum.FINISH;
                    // 设置跳过标识与上一步步骤ID
                    skipFlag = Boolean.TRUE;
                    previousStepId = maintenanceFundsBusiness.getStepId();
                    // 一次拨付直接办理结束
                    R<GwjConfStep> gwjConfStepR = remoteGwjConfigService.selectNextGwjConfStepByFlagId(maintenanceFundsBusiness.getBizFlagId(), maintenanceFundsBusiness.getStepId(), SecurityConstants.INNER);
                    if (R.isError(gwjConfStepR)) {
                        throw new ServiceException(gwjConfStepR.getMsg());
                    }
                    if (ObjectUtil.isNull(gwjConfStepR.getData())) {
                        throw new ServiceException(gwjConfStepR.getMsg());
                    }
                    // 当前业务设置为财务对账流程
                    maintenanceFundsBusiness.setStepId(gwjConfStepR.getData().getStepId());
                    // 发送外网步骤回调
                    String freexamineJsonMsg = resultNotify(maintenanceFundsBusiness);
                    if (ObjectUtil.isEmpty(freexamineJsonMsg)) {
                        throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                    }
                    // 步骤回调修改为远程调用
                    try {
                        remoteGwjExpendService.resultNotify(freexamineJsonMsg, SecurityConstants.INNER).getData();
                    } catch (Exception e) {
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) + "支出外网步骤回调一次:" + e.getMessage());
                    }
                }
                // ---------------------------20230831取消步骤回调 s--------------------------------------
                // 发送外网步骤回调
                // String freexamineJsonMsg = resultNotify(maintenanceFundsBusiness);
                // if (ObjectUtil.isEmpty(freexamineJsonMsg)) {
                // throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                // }
                // // 步骤回调修改为远程调用
                // try {
                // remoteGwjExpendService.resultNotify(freexamineJsonMsg, SecurityConstants.INNER).getData();
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // ---------------------------20230831取消步骤回调 e--------------------------------------
                break;
            // 4、财务对账提交（二次拨付才存在的流程）
            case FINANCE_CHECK:
                GwjMaintenanceFundsBusinessInfo info = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(maintenanceFundsBusiness.getBizId());
                if (AppropriationWayEnum.ONE.getCode().equals(info.getAppropriationWay())) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "一次拨付不存在财务对账,请重新提交");
                }
                if (!GwjCheckAccountStatus.CHECK_SUCCESS.getCode().equals(String.valueOf(maintenanceFundsBusiness.getFinanceCheck()))) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "请先完成财务对账");
                }
                statusEnum = BusinessStatusEnum.FINISH;
                // ---------------------------20230906申请阶段二次拨付保留步骤回调 s--------------------------------------
                if (AppropriationWayEnum.TWO.getCode().equals(info.getAppropriationWay())) {
                    // 发送外网步骤回调
                    String financeCheckJsonMsg = this.resultNotify(maintenanceFundsBusiness);
                    if (ObjectUtil.isEmpty(financeCheckJsonMsg)) {
                        throw new ServiceException("公维金支出外网回调步骤参数不能为空");
                    }
                    // 步骤回调修改为远程调用
                    // try {
                    // remoteGwjExpendService.resultNotify(financeCheckJsonMsg, SecurityConstants.INNER).getData();
                    // } catch (Exception e) {
                    // throw new
                    // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                    // "支出外网步骤回调一次:" + e.getMessage());
                    // }
                    R<Boolean> result = remoteGwjExpendService.resultNotify(financeCheckJsonMsg, SecurityConstants.INNER);
                    if (R.isError(result)) {
                        throw new ServiceException("[财务对账提交]支出外网步骤回调失败1:" + result.getMsg());
                    }
                    if (!result.getData()) {
                        throw new ServiceException("[财务对账提交]支出外网步骤回调失败2:" + result.getMsg());
                    }
                }
                // ---------------------------20230906申请阶段二次拨付保留步骤回调 e--------------------------------------
                break;
            default:
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "业务状态不一致,请重新提交");
        }
        Long stepId;
        try {
            R<GwjConfStep> r = remoteGwjConfigService.selectNextGwjConfStepByFlagId(maintenanceFundsBusiness.getBizFlagId(), maintenanceFundsBusiness.getStepId(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException(r.getMsg());
            }
            stepId = r.getData().getStepId();
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]异常,异常信息: [{}]", e);
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]异常");
        }
        Optional.of(maintenanceFundsBusinessMapper.updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                setStepId(stepId);
                setStatus(statusEnum.getCode());
                setBizId(submitRequest.getBizId());
                setCurrentOperId(submitRequest.getCurrentOperId());
                setCurrentOperName(submitRequest.getCurrentOperName());
                setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "GwjMaintenanceFundsBusiness更新失败");
        });

        GwjMaintenanceFundsBusinessLog gwjMaintenanceFundsBusinessLog = new GwjMaintenanceFundsBusinessLog();
        gwjMaintenanceFundsBusinessLog.setResult(GwjBusinessLogResult.SUBMIT.getCode());
        gwjMaintenanceFundsBusinessLog.setContent(submitRequest.getContent());
        gwjMaintenanceFundsBusinessLog.setBizId(maintenanceFundsBusiness.getBizId());
        // 判断步骤是否跳过
        if (skipFlag) {
            // 赋值跳过上一步步骤ID
            gwjMaintenanceFundsBusinessLog.setStepId(previousStepId);
        } else {
            // 赋值正常业务步骤ID
            gwjMaintenanceFundsBusinessLog.setStepId(maintenanceFundsBusiness.getStepId());
        }
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(gwjMaintenanceFundsBusinessLog);
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "GwjMaintenanceFundsBusinessLog新增失败");
        }
        // 数据发送外网拨付申请
        if ((skipFlag && ObjectUtil.equal(BusinessStatusEnum.REEXAMINE.getCode(), submitRequest.getStatus())) || (!skipFlag && ObjectUtil.equal(BusinessStatusEnum.FINANCE_CHECK.getCode(), submitRequest.getStatus()))) {
            insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
                {
                    setBizId(maintenanceFundsBusiness.getBizId());
                    setResult(GwjBusinessLogResult.FINISH.getCode());
                    setAcceptTime(LocalDateTimeUtil.offset(LocalDateTime.now(), 1, ChronoUnit.SECONDS));
                    try {
                        R<GwjConfStep> r = remoteGwjConfigService.getFinalStep(maintenanceFundsBusiness.getBizFlagId(), SecurityConstants.INNER);
                        if (R.isError(r)) {
                            throw new ServiceException(r.getMsg());
                        }
                        if (ObjectUtil.isNull(r.getData())) {
                            throw new ServiceException(r.getMsg());
                        }
                        setStepId(r.getData().getStepId());
                    } catch (Exception e) {
                        log.error("远程调用 -> [remoteGwjConfigService][getFinalStep]异常,异常信息: [{}]", e);
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "远程调用 -> [remoteGwjConfigService][getFinalStep]异常");
                    }
                }
            });
            if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT) + "签署意见GwjMaintenanceFundsBusinessLog新增失败");
            }
            reexamine(maintenanceFundsBusiness);
        }
        return FlagStatusEnum.SUC.getCode();
    }

    public int reexamine(GwjMaintenanceFundsBusiness maintenanceFundsBusiness) {
        List<GwjMaintenanceFundsBusinessHouse> maintenanceFundsBusinessHouseList = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessHouseList)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "未获取到对应的支出业务房屋数据List<GwjMaintenanceFundsBusinessHouse>");
        }
        List<GwjMaintenanceFundsBusinessBuild> maintenanceFundsBusinessBuildList = maintenanceFundsBusinessBuildService.selectGwjMaintenanceFundsBusinessBuildList(new GwjMaintenanceFundsBusinessBuild() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessBuildList)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "未获取到对应的支出业务楼栋数据List<GwjMaintenanceFundsBusinessBuild>");
        }
        List<GwjMaintenanceFundsBusinessOwner> maintenanceFundsBusinessOwnerList = maintenanceFundsBusinessOwnerService.selectGwjMaintenanceFundsBusinessOwnerList(new GwjMaintenanceFundsBusinessOwner() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessOwnerList)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "未获取到对应的支出业务业主数据maintenanceFundsBusinessOwnerList");
        }
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(maintenanceFundsBusiness.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessCommunity)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "未获取到对应的支出业务项目数据GwjMaintenanceFundsBusinessCommunity");
        }
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(maintenanceFundsBusiness.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessInfo)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "未获取到对应的支出维修资金使用申请工程信息GwjMaintenanceFundsBusinessInfo");
        }
        PreAcceptSubmitMessage acceptSubmitMessage = new PreAcceptSubmitMessage() {
            {
                setMaintenanceFundsBusiness(maintenanceFundsBusiness);
                setMaintenanceFundsBusinessInfo(maintenanceFundsBusinessInfo);
                setMaintenanceFundsBusinessCommunity(maintenanceFundsBusinessCommunity);
                setMaintenanceFundsBusinessBuildList(maintenanceFundsBusinessBuildList);
                setMaintenanceFundsBusinessHouseList(maintenanceFundsBusinessHouseList);
                setMaintenanceFundsBusinessOwnerList(maintenanceFundsBusinessOwnerList);
            }
        };
        String tag = maintenanceFundsBusinessConfiguration.appropriateTagProperties().getFormalSubmit();
        MqSendResult mqSendResult = mqSendMessageHandler.syncSend(new MaintenanceFundsMqMessageBody() {
            {
                setJsonMsg(JSONUtil.toJsonStr(acceptSubmitMessage));
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        }, new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessAppropriateSendRequest(tag, null));
        if (mqSendResult.isSuccess()) {
            return FlagStatusEnum.SUC.getCode();
        } else {
            log.error("资金申请正式受理MQ消息发送异常 -> [{}]", mqSendResult.getMessage());
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.SUBMIT_INTRANET) + "资金申请正式受理MQ消息发送异常");
        }
    }

    @Override
    public int confirmReceipt(ConfirmReceiptDTO confirmReceiptDTO) {
        if (ObjectUtil.equal(confirmReceiptDTO.getAllReceiveFlag(), FlagStatusEnum.SUC.getCode())) {
            return maintenanceFundsBusinessAttachmentService.updateGwjMaintenanceFundsBusinessAttachment(new GwjMaintenanceFundsBusinessAttachment() {
                {
                    setReceiveFlag(FlagStatusEnum.SUC.getCode());
                    setServerIdentification(confirmReceiptDTO.getServerIdentification());
                }
            });
        } else {
            return maintenanceFundsBusinessAttachmentService.updateBatchGwjMaintenanceFundsBusinessAttachment(new ConfirmReceiptDTO() {
                {
                    setReceiveFlag(FlagStatusEnum.SUC.getCode());
                    setAttachmentIdList(confirmReceiptDTO.getAttachmentIdList());
                }
            });
        }
    }

    @Override
    public int cancelReceipt(Long attachmentId) {
        return maintenanceFundsBusinessAttachmentService.updateGwjMaintenanceFundsBusinessAttachment(new GwjMaintenanceFundsBusinessAttachment() {
            {
                setAttachmentId(attachmentId);
                setReceiveFlag(FlagStatusEnum.FAL.getCode());
            }
        });
    }

    @Override
    public int fallback(SubmitRequest submitRequest) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(submitRequest.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "未获取到对应的公共维修资金业务信息");
        }
        // 能回退的步骤只有初审跟复审
        BusinessStatusEnum statusEnum;
        BusinessStatusEnum oldStatusEnum = BusinessStatusEnum.transfer(maintenanceFundsBusiness.getStatus());
        switch (oldStatusEnum) {
            // 1.初审提交阶段
            case FIRST_INSTANCE:
                statusEnum = BusinessStatusEnum.TAKE_PARTS;
                // --------------------------20230906 取消 s--------------------------------
                // 支出外网业务回调参数赋值
                // PreAcceptMessage firstInstancePreAcceptMessage = new PreAcceptMessage();
                // firstInstancePreAcceptMessage.setContent(submitRequest.getContent());
                // firstInstancePreAcceptMessage.setAcceptTime(LocalDateTime.now());
                // firstInstancePreAcceptMessage.setOperId(SecurityUtils.getLoginUser().getUserid());
                // firstInstancePreAcceptMessage.setOperName(SecurityUtils.getLoginUser().getUsername());
                // firstInstancePreAcceptMessage.setStepId(maintenanceFundsBusiness.getStepId());
                // firstInstancePreAcceptMessage.setOutServerIdentification(maintenanceFundsBusiness.getOutServerIdentification());
                // if (ObjectUtil.isEmpty(firstInstancePreAcceptMessage)) {
                // throw new ServiceException("外网支出回退步骤参数不能为空");
                // }
                // // 支出外网业务步骤回退
                // try {
                // remoteGwjExpendService.rollbackResultNotify(JSONUtil.toJsonStr(firstInstancePreAcceptMessage),
                // SecurityConstants.INNER);
                //
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // --------------------------20230906 取消 e--------------------------------
                break;
            // 2.复审提交阶段
            case REEXAMINE:
                // --------------------------20230906 取消 s--------------------------------
                // 支出外网业务回调参数赋值
                // PreAcceptMessage reexaminePreAcceptMessage = new PreAcceptMessage();
                // reexaminePreAcceptMessage.setContent(submitRequest.getContent());
                // reexaminePreAcceptMessage.setAcceptTime(LocalDateTime.now());
                // reexaminePreAcceptMessage.setOperId(SecurityUtils.getLoginUser().getUserid());
                // reexaminePreAcceptMessage.setOperName(SecurityUtils.getLoginUser().getUsername());
                // reexaminePreAcceptMessage.setStepId(maintenanceFundsBusiness.getStepId());
                // reexaminePreAcceptMessage.setOutServerIdentification(maintenanceFundsBusiness.getOutServerIdentification());
                // if (ObjectUtil.isEmpty(reexaminePreAcceptMessage)) {
                // throw new ServiceException("外网支出回退步骤参数不能为空");
                // }
                // // 支出外网业务步骤回退
                // try {
                // remoteGwjExpendService.rollbackResultNotify(JSONUtil.toJsonStr(reexaminePreAcceptMessage),
                // SecurityConstants.INNER);
                //
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // --------------------------20230906 取消 e--------------------------------
                GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(submitRequest.getBizId());
                if (ObjectUtil.equal(AppropriationWayEnum.TWO.getCode(), maintenanceFundsBusinessInfo.getAppropriationWay())) {
                    if (ObjectUtil.equal(FlagStatusEnum.SUC.getCode(), maintenanceFundsBusiness.getFinancialJournalFlag())) {
                        Optional.ofNullable(((IGwjMaintenanceFundsBusinessService)AopContext.currentProxy()).updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
                            {
                                setBizId(maintenanceFundsBusiness.getBizId());
                                setFinancialJournalFlag(FlagStatusEnum.FAL.getCode());
                            }
                        })).<ServiceException>orElseThrow(() -> {
                            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "公共维修资金业务信息更新失败");
                        });
                        Optional.ofNullable(maintenanceFundsBusinessInfoService.updateGwjMaintenanceFundsBusinessInfo(new GwjMaintenanceFundsBusinessInfo() {
                            {
                                setBizId(maintenanceFundsBusiness.getBizId());
                                setActualAllocatedTime(null);
                                setActualAllocatedSettlementAmount(BigDecimal.ZERO);
                            }
                        })).<ServiceException>orElseThrow(() -> {
                            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "维修资金使用申请工程信息GwjMaintenanceFundsBusinessInfo更新失败");
                        });
                        // 查询财务流水
                        GwjFinanceAccountMain gwjFinanceAccountMain = remoteGwjFinanceService.getGwjFinanceAccountMain(new GwjFinanceAccountMain() {
                            {
                                setBizId(maintenanceFundsBusiness.getBizId());
                                setBizNum(maintenanceFundsBusiness.getBizNum());
                                setBizFlagId(maintenanceFundsBusiness.getBizFlagId());
                            }
                        }, SecurityConstants.INNER).getData();
                        // 判断财务流水是否存在
                        if (ObjectUtil.isNotEmpty(gwjFinanceAccountMain)) {
                            try {
                                R<Integer> r = remoteGwjFinanceService.deleteGwjFinanceAccountMain(new GwjFinanceAccountMain() {
                                    {
                                        setBizId(maintenanceFundsBusiness.getBizId());
                                        setBizNum(maintenanceFundsBusiness.getBizNum());
                                        setBizFlagId(maintenanceFundsBusiness.getBizFlagId());
                                    }
                                }, SecurityConstants.INNER);
                                if (R.isError(r)) {
                                    throw new ServiceException(r.getMsg());
                                }
                                if (ObjectUtil.isNull(r.getData()) || ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), r.getData())) {
                                    throw new ServiceException("删除总账流水异常");
                                }
                            } catch (Exception e) {
                                log.error("远程调用 -> [remoteGwjFinanceService][deleteGwjFinanceAccountMain]异常: [{}]", e);
                                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "远程调用 -> [remoteGwjFinanceService][deleteGwjFinanceAccountMain]异常");
                            }
                        }
                    }
                }
                statusEnum = BusinessStatusEnum.FIRST_INSTANCE;
                break;
            case FINANCE_CHECK:
                // 查询业务详情信息
                GwjMaintenanceFundsBusinessInfo info = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(submitRequest.getBizId());
                // 判断业务步骤是否为二次拨付
                if (!ObjectUtil.equal(AppropriationWayEnum.TWO.getCode(), info.getAppropriationWay())) {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "业务步骤异常");
                }
                // 重置生成财务流水状态
                Optional.ofNullable(((IGwjMaintenanceFundsBusinessService)AopContext.currentProxy()).updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
                    {
                        setBizId(maintenanceFundsBusiness.getBizId());
                        setFinancialJournalFlag(FlagStatusEnum.FAL.getCode());
                    }
                })).<ServiceException>orElseThrow(() -> {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "公共维修资金业务信息更新失败");
                });
                // 重置实际拨款金额与实际拨款时间
                Optional.ofNullable(maintenanceFundsBusinessInfoService.updateGwjMaintenanceFundsBusinessInfo(new GwjMaintenanceFundsBusinessInfo() {
                    {
                        setBizId(maintenanceFundsBusiness.getBizId());
                        setActualAllocatedTime(null);
                        setActualAllocatedSettlementAmount(BigDecimal.ZERO);
                    }
                })).<ServiceException>orElseThrow(() -> {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "维修资金使用申请工程信息GwjMaintenanceFundsBusinessInfo更新失败");
                });
                // 删除总账流水
                try {
                    R<Integer> r = remoteGwjFinanceService.deleteGwjFinanceAccountMain(new GwjFinanceAccountMain() {
                        {
                            setBizId(maintenanceFundsBusiness.getBizId());
                            setBizNum(maintenanceFundsBusiness.getBizNum());
                            setBizFlagId(maintenanceFundsBusiness.getBizFlagId());
                        }
                    }, SecurityConstants.INNER);
                    if (R.isError(r)) {
                        throw new ServiceException(r.getMsg());
                    }
                    if (ObjectUtil.isNull(r.getData()) || ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), r.getData())) {
                        throw new ServiceException("删除总账流水异常");
                    }
                } catch (Exception e) {
                    log.error("远程调用 -> [remoteGwjFinanceService][deleteGwjFinanceAccountMain]异常: [{}]", e);
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "远程调用 -> [remoteGwjFinanceService][deleteGwjFinanceAccountMain]异常");
                }
                // 重置决算总金额
                Optional.ofNullable(maintenanceFundsBusinessInfoService.updateGwjMaintenanceFundsBusinessInfo(new GwjMaintenanceFundsBusinessInfo() {
                    {
                        setBizId(maintenanceFundsBusiness.getBizId());
                        setActualAllocatedTime(null);
                        setActualAllocatedSettlementAmount(BigDecimal.ZERO);
                    }
                })).<ServiceException>orElseThrow(() -> {
                    throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "维修资金使用申请工程信息GwjMaintenanceFundsBusinessInfo更新失败");
                });
                if (ObjectUtil.equal(Integer.valueOf(GwjCheckAccountStatus.CHECK_SUCCESS.getCode()), maintenanceFundsBusiness.getFinanceCheck())) {
                    Optional.ofNullable(maintenanceFundsBusinessMapper.updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
                        {
                            setBizId(maintenanceFundsBusiness.getBizId());
                            // 更新财务对账状态
                            setFinanceCheck(Integer.valueOf(GwjCheckAccountStatus.NOT_CHECK.getCode()));
                            // 更新生成总帐流水状态
                            setFinancialJournalFlag(Integer.valueOf(GwjCheckAccountStatus.NOT_CHECK.getCode()));
                        }
                    })).<ServiceException>orElseThrow(() -> {
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "财务对账回退失败");
                    });
                }
                // --------------------------20230906 取消 s--------------------------------
                // 支出外网业务回调参数赋值
                // PreAcceptMessage financeCheckPreAcceptMessage = new PreAcceptMessage();
                // financeCheckPreAcceptMessage.setContent(submitRequest.getContent());
                // financeCheckPreAcceptMessage.setAcceptTime(LocalDateTime.now());
                // financeCheckPreAcceptMessage.setOperId(SecurityUtils.getLoginUser().getUserid());
                // financeCheckPreAcceptMessage.setOperName(SecurityUtils.getLoginUser().getUsername());
                // financeCheckPreAcceptMessage.setStepId(maintenanceFundsBusiness.getStepId());
                // financeCheckPreAcceptMessage.setOutServerIdentification(maintenanceFundsBusiness.getOutServerIdentification());
                // if (ObjectUtil.isEmpty(financeCheckPreAcceptMessage)) {
                // throw new ServiceException("外网支出回退步骤参数不能为空");
                // }
                // // 支出外网业务步骤回退
                // try {
                // remoteGwjExpendService.rollbackResultNotify(JSONUtil.toJsonStr(financeCheckPreAcceptMessage),
                // SecurityConstants.INNER);
                //
                // } catch (Exception e) {
                // throw new
                // ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) +
                // "支出外网步骤回调一次:" + e.getMessage());
                // }
                // --------------------------20230906 取消 e--------------------------------
                statusEnum = BusinessStatusEnum.REEXAMINE;
                break;
            default:
                throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "业务状态不一致,请重新提交");
        }
        Long stepId;
        try {
            R<GwjConfStep> r = remoteGwjConfigService.selectPreviousGwjConfStepByFlagId(maintenanceFundsBusiness.getBizFlagId(), maintenanceFundsBusiness.getStepId(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException(r.getMsg());
            }
            stepId = r.getData().getStepId();
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][selectPreviousGwjConfStepByFlagId]异常,异常信息: [{}]", e);
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "远程调用 -> [remoteGwjConfigService][selectPreviousGwjConfStepByFlagId]异常");
        }
        List<GwjMaintenanceFundsBusinessLog> maintenanceFundsBusinessLogList = maintenanceFundsBusinessLogService.selectGwjMaintenanceFundsBusinessLogList(new GwjMaintenanceFundsBusinessLog() {
            {
                setStepId(stepId);
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        Optional.ofNullable(maintenanceFundsBusinessLogList).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "未获取到对应的签署意见列表");
        });
        GwjMaintenanceFundsBusinessLog maintenanceFundsBusinessLog = maintenanceFundsBusinessLogList.stream().max(Comparator.comparing(GwjMaintenanceFundsBusinessLog::getCreateTime)).get();
        Optional.ofNullable(maintenanceFundsBusinessMapper.updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                setStepId(stepId);
                setStatus(statusEnum.getCode());
                setBizId(maintenanceFundsBusiness.getBizId());
                setServerStatus(BusinessServerStatusEnum.FALLBACK.getCode());
                setCurrentOperId(maintenanceFundsBusinessLog.getOperId());
                setCurrentOperName(maintenanceFundsBusinessLog.getOperName());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.FALLBACK) + "GwjMaintenanceFundsBusiness更新失败");
        });
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            {
                setResult(GwjBusinessLogResult.FALLBACK.getCode());
                setContent(submitRequest.getContent());
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.CONFIRM_ACCEPTANCE) + "签署意见GwjMaintenanceFundsBusinessLog新增失败");
        }
        return FlagStatusEnum.SUC.getCode();
    }

    @Override
    public OneTimeNotificationDTO oneTimeNotification(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        List<GwjMaintenanceFundsBusinessAttachment> maintenanceFundsBusinessAttachmentList = maintenanceFundsBusinessAttachmentService.selectGwjMaintenanceFundsBusinessAttachmentList(new GwjMaintenanceFundsBusinessAttachment() {
            {
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessAttachmentList)) {
            return null;
        }
        // 1.找出已收件
        List<GwjMaintenanceFundsBusinessAttachment> receiveAttachmentList = maintenanceFundsBusinessAttachmentList.stream().filter(attachment -> attachment.getReceiveFlag().equals(FlagStatusEnum.SUC.getCode())).distinct().collect(Collectors.toList());
        // 2.找出未收件
        List<GwjMaintenanceFundsBusinessAttachment> noReceiveAttachmentList = maintenanceFundsBusinessAttachmentList.stream().filter(attachment -> attachment.getReceiveFlag().equals(FlagStatusEnum.FAL.getCode())).distinct().collect(Collectors.toList());

        List<String> possessMaintenanceList = ListUtil.toList();
        receiveAttachmentList.forEach(attachment -> {
            BusinessAttachmentServerTypeEnum serverTypeEnum = BusinessAttachmentServerTypeEnum.transfer(attachment.getServerType());
            // 去重
            if (!possessMaintenanceList.contains(serverTypeEnum.getInfo())) {
                possessMaintenanceList.add(serverTypeEnum.getInfo());
            }
        });

        List<String> noPossessMaintenanceList = ListUtil.toList();
        noReceiveAttachmentList.forEach(attachment -> {
            BusinessAttachmentServerTypeEnum serverTypeEnum = BusinessAttachmentServerTypeEnum.transfer(attachment.getServerType());
            // 去重
            if (!noPossessMaintenanceList.contains(serverTypeEnum.getInfo())) {
                noPossessMaintenanceList.add(serverTypeEnum.getInfo());
            }
        });
        return new OneTimeNotificationDTO() {
            {
                setPhone(maintenanceFundsBusiness.getPhone());
                setBizName(maintenanceFundsBusiness.getBizName());
                setAddress(maintenanceFundsBusiness.getAddress());
                setContacts(maintenanceFundsBusiness.getContacts());
                setPossessMaintenanceList(possessMaintenanceList);
                setNoPossessMaintenanceList(noPossessMaintenanceList);
                setConstructionUnit(maintenanceFundsBusinessInfo.getConstructionUnit());
                setAcceptTime(maintenanceFundsBusiness.getAcceptTime().toLocalDate());
                setClosingTime(WeekdayUtils.targetDate(maintenanceFundsBusiness.getAcceptTime().toLocalDate(), 5L));
                setBusinessNum(maintenanceFundsBusiness.getBizNum());
            }
        };
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editForm(EditFormRequest editFormRequest) {
        if (ObjectUtil.isNull(editFormRequest.getActualAllocatedSettlementAmount()) || ObjectUtil.isNull(editFormRequest.getActualAllocatedTime())) {
            return FlagStatusEnum.FAL.getCode();
        }
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(editFormRequest.getBizId());
        if (ObjectUtil.equal(1, CompareUtil.compare(editFormRequest.getActualAllocatedSettlementAmount(), maintenanceFundsBusinessInfo.getBudgetAppropriationAmount()))) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.EDIT_FORM) + "实际拨出金额不能大于预算拨出金额");
        }
        Optional.ofNullable(maintenanceFundsBusinessInfoService.updateGwjMaintenanceFundsBusinessInfo(new GwjMaintenanceFundsBusinessInfo() {
            {
                setBizId(editFormRequest.getBizId());
                setActualAllocatedTime(editFormRequest.getActualAllocatedTime());
                setActualAllocatedSettlementAmount(editFormRequest.getActualAllocatedSettlementAmount());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.EDIT_FORM) + "维修资金使用申请工程信息GwjMaintenanceFundsBusinessInfo更新失败");
        });
        return FlagStatusEnum.SUC.getCode();
    }

    @Override
    public Application4ApprovalDTO getApplication4Approval(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(bizId);
        List<GwjMaintenanceFundsBusinessHouse> houseList = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            /**
             *
             */
            private static final long serialVersionUID = 6346060379532176110L;

            {
                setSelectFlag(SelectFlagEnum.SELECT.getCode());
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        return new Application4ApprovalDTO() {
            {
                setPhone(maintenanceFundsBusiness.getPhone());
                setContacts(maintenanceFundsBusiness.getContacts());
                setBizId(maintenanceFundsBusiness.getBizId());
                setTotalHouseholds(maintenanceFundsBusinessInfo.getTotalHouseholds());
                setMaintenanceItems(maintenanceFundsBusinessInfo.getMaintenanceItems());
                setApplicationUnitName(maintenanceFundsBusinessInfo.getApplicationUnitName());
                setProjectBudgetAmount(maintenanceFundsBusinessInfo.getProjectBudgetAmount());
                // 实时查询当前小区所有的当前余额
                setTotalMoney(BigDecimal.ZERO);
                // 查询涉及用户的面积
                setPartialPortionArea(BigDecimal.ZERO);
                // 实时查询涉及用户的当前余额
                setProprietaryPortionMoney(BigDecimal.ZERO);
                List<GwjBaseHouse> baseHouseList = baseHouseService.selectGwjBaseListByCommunityId(maintenanceFundsBusinessCommunity.getCommunityId());
                if (CollectionUtil.isNotEmpty(baseHouseList)) {
                    setTotalMoney(baseHouseList.stream().map(baseHouse -> baseHouse.getCurrentMoney()).reduce(BigDecimal.ZERO, BigDecimal::add));
                    List<GwjBaseHouse> portionBaseHouseList = baseHouseList.stream().filter(item -> houseList.stream().map(house -> house.getHouseCode()).collect(Collectors.toList()).contains(item.getHouseCode())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(baseHouseList)) {
                        setProprietaryPortionMoney(portionBaseHouseList.stream().map(baseHouse -> baseHouse.getCurrentMoney()).reduce(BigDecimal.ZERO, BigDecimal::add));
                        setPartialPortionArea(portionBaseHouseList.stream().map(baseHouse -> ObjectUtil.equal(BigDecimal.ZERO, baseHouse.getActualSize()) ? baseHouse.getForecastSize() : baseHouse.getActualSize()).reduce(BigDecimal.ZERO, BigDecimal::add));
                    }
                }
                GwjMaintenanceFundsBusinessAttachment maintenanceFundsBusinessAttachment = maintenanceFundsBusinessAttachmentService.getGwjMaintenanceFundsBusinessAttachment(new GwjMaintenanceFundsBusinessAttachment() {
                    {
                        setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                        setServerType(BusinessAttachmentServerTypeEnum.APPLICATION_APPROVAL.getCode());
                        setType(BusinessAttachmentTypeEnum.REPORT.getCode());
                    }
                });
                if (ObjectUtil.isNotNull(maintenanceFundsBusinessAttachment)) {
                    setAttachmentId(maintenanceFundsBusinessAttachment.getAttachmentId());
                    Application4ApprovalDTO applicationReport = JSONUtil.toBean(maintenanceFundsBusinessAttachment.getContent(), Application4ApprovalDTO.class);
                    setPreReviewOpinions(applicationReport.getPreReviewOpinions());
                    setOrganizerOpinions(applicationReport.getOrganizerOpinions());
                    setExamineOpinions(applicationReport.getExamineOpinions());
                }
            }
        };
    }

    @Override
    public List<GwjMaintenanceFundsBusinessBuild> getSelectBuilds(Long bizId) {
        return maintenanceFundsBusinessBuildService.selectGwjMaintenanceFundsBusinessBuildList(new GwjMaintenanceFundsBusinessBuild() {
            {
                setBizId(bizId);
            }
        });
    }

    @Override
    public List<GwjMaintenanceFundsBusinessHouse> getHouseList(HousesUnderBuildRequest housesUnderBuildRequest) {
        return maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setBizId(housesUnderBuildRequest.getBizId());
                setBuildCode(housesUnderBuildRequest.getBuildCode());
                setAreaId(housesUnderBuildRequest.getAreaId());
            }
        });
    }

    public Appropriate4ApproveDTO getAppropriate4Approval(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(bizId);
        List<String> attachmentNameList = maintenanceFundsBusinessAttachmentService.getGwjMaintenanceFundsBusinessAttachmentList(new GetAttachmentInfoRequest() {
            {
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        }).stream().map(item -> {
            return BusinessAttachmentServerTypeEnum.getInfoStr(item.getServerType());
        }).collect(Collectors.toList());
        List<GwjMaintenanceFundsBusinessHouse> houseList = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setSelectFlag(SelectFlagEnum.SELECT.getCode());
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        return new Appropriate4ApproveDTO() {
            {
                setTotalSettlementAmount(maintenanceFundsBusinessInfo.getTotalSettlementAmount());
                setConstructionUnit(maintenanceFundsBusinessInfo.getConstructionUnit());
                setPhone(maintenanceFundsBusiness.getPhone());
                setContacts(maintenanceFundsBusiness.getContacts());
                setBizId(maintenanceFundsBusiness.getBizId());
                setTotalHouseholds(maintenanceFundsBusinessInfo.getTotalHouseholds());
                setMaintenanceItems(maintenanceFundsBusinessInfo.getMaintenanceItems());
                setApplicationUnitName(maintenanceFundsBusinessInfo.getApplicationUnitName());
                setProjectBudgetAmount(maintenanceFundsBusinessInfo.getProjectBudgetAmount());
                setPayeeName(maintenanceFundsBusinessInfo.getPayeeName());
                setBankDeposit(maintenanceFundsBusinessInfo.getBankDeposit());
                setConstructionUnit(maintenanceFundsBusinessInfo.getConstructionUnit());
                setCollectionAccount(maintenanceFundsBusinessInfo.getCollectionAccount());
                setBudgetAppropriationAmount(maintenanceFundsBusinessInfo.getBudgetAppropriationAmount());
                String examineOpinions = ColumnUtil.getFieldName(Appropriate4ApproveDTO::getExamineOpinions);
                String organizerOpinions = ColumnUtil.getFieldName(Appropriate4ApproveDTO::getOrganizerOpinions);
                String preReviewOpinions = ColumnUtil.getFieldName(Appropriate4ApproveDTO::getPreReviewOpinions);
                setActualAllocatedTime(maintenanceFundsBusinessInfo.getActualAllocatedTime());
                setCommunityName(maintenanceFundsBusinessCommunity.getCommunityName());
                setAttachmentNameList(attachmentNameList);
                Appropriate4ApproveDTO appropriate4Approve = maintenanceFundsBusinessAttachmentService.getContent2Entity(Appropriate4ApproveDTO.class, BusinessAttachmentServerTypeEnum.SETTLEMENT_DISBURSEMENT_APPROVAL.getCode(), maintenanceFundsBusiness.getServerIdentification(), examineOpinions, organizerOpinions, preReviewOpinions);
                if (ObjectUtil.isNotNull(appropriate4Approve)) {
                    setExamineOpinions(appropriate4Approve.getExamineOpinions());
                    setOrganizerOpinions(appropriate4Approve.getOrganizerOpinions());
                    setPreReviewOpinions(appropriate4Approve.getPreReviewOpinions());
                }
                // 实时查询当前小区所有的当前余额
                setTotalMoney(BigDecimal.ZERO);
                // 查询涉及用户的面积
                setPartialPortionArea(BigDecimal.ZERO);
                // 实时查询涉及用户的当前余额
                setProprietaryPortionMoney(BigDecimal.ZERO);
                List<GwjBaseHouse> baseHouseList = baseHouseService.selectGwjBaseListByCommunityId(maintenanceFundsBusinessCommunity.getCommunityId());
                if (CollectionUtil.isNotEmpty(baseHouseList)) {
                    setTotalMoney(baseHouseList.stream().map(baseHouse -> baseHouse.getCurrentMoney()).reduce(BigDecimal.ZERO, BigDecimal::add));
                    List<GwjBaseHouse> portionBaseHouseList = baseHouseList.stream().filter(item -> houseList.stream().map(house -> house.getHouseCode()).collect(Collectors.toList()).contains(item.getHouseCode())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(baseHouseList)) {
                        setProprietaryPortionMoney(portionBaseHouseList.stream().map(baseHouse -> baseHouse.getCurrentMoney()).reduce(BigDecimal.ZERO, BigDecimal::add));
                        setPartialPortionArea(portionBaseHouseList.stream().map(baseHouse -> ObjectUtil.equal(BigDecimal.ZERO, baseHouse.getActualSize()) ? baseHouse.getForecastSize() : baseHouse.getActualSize()).reduce(BigDecimal.ZERO, BigDecimal::add));
                    }
                }
                GwjMaintenanceFundsBusinessAttachment maintenanceFundsBusinessAttachment = maintenanceFundsBusinessAttachmentService.getGwjMaintenanceFundsBusinessAttachment(new GwjMaintenanceFundsBusinessAttachment() {
                    {
                        setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                        setServerType(BusinessAttachmentServerTypeEnum.SETTLEMENT_DISBURSEMENT_APPROVAL.getCode());
                        setType(BusinessAttachmentTypeEnum.REPORT.getCode());
                    }
                });
                if (ObjectUtil.isNotNull(maintenanceFundsBusinessAttachment)) {
                    Application4ApprovalDTO application4Approval = JSONUtil.toBean(maintenanceFundsBusinessAttachment.getContent(), Application4ApprovalDTO.class);
                    setAttachmentId(maintenanceFundsBusinessAttachment.getAttachmentId());
                    setPreReviewOpinions(application4Approval.getPreReviewOpinions());
                    setOrganizerOpinions(application4Approval.getOrganizerOpinions());
                    setExamineOpinions(application4Approval.getExamineOpinions());
                }
            }
        };
    }

    @Override
    public int generateFinancialJournal(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        if (ObjectUtil.equal(FlagStatusEnum.SUC.getCode(), maintenanceFundsBusiness.getFinancialJournalFlag())) {
            throw new ServiceException("请勿重复生财务流水");
        }
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        if (ObjectUtil.notEqual(AppropriationWayEnum.TWO.getCode(), maintenanceFundsBusinessInfo.getAppropriationWay())) {
            throw new ServiceException("生成总账流水异常");
        }
        if (ObjectUtil.equal(BigDecimal.ZERO, maintenanceFundsBusinessInfo.getActualAllocatedSettlementAmount()) || ObjectUtil.isNull(maintenanceFundsBusinessInfo.getActualAllocatedSettlementAmount())) {
            throw new ServiceException("请先填写实际拨款金额");
        }
        if (ObjectUtil.isNull(maintenanceFundsBusinessInfo.getActualAllocatedTime())) {
            throw new ServiceException("请先填写实际拨款时间");
        }
        // 设置总账参数
        GwjFinanceAccountMain accountMain = new GwjFinanceAccountMain();
        accountMain.setBizId(maintenanceFundsBusiness.getBizId());
        accountMain.setBizNum(maintenanceFundsBusiness.getBizNum());
        accountMain.setBizFlagId(maintenanceFundsBusiness.getBizFlagId());
        accountMain.setBankName(maintenanceFundsBusinessInfo.getBankDeposit());
        accountMain.setBankAccount(maintenanceFundsBusinessInfo.getCollectionAccount());
        accountMain.setIncomeMoney(BigDecimal.ZERO);
        accountMain.setPayMoney(maintenanceFundsBusinessInfo.getActualAllocatedSettlementAmount());
        accountMain.setDealTime(DateUtil.date(maintenanceFundsBusinessInfo.getActualAllocatedTime()));
        accountMain.setCheckStatus(GwjCheckAccountStatus.NOT_CHECK.getCode());
        accountMain.setCheckType(GwjCheckAccountType.HANDWORK.getCode());
        accountMain.setCompanyName(maintenanceFundsBusinessInfo.getApplicationUnitName());
        accountMain.setProjectName(maintenanceFundsBusiness.getBizName());
        accountMain.setTotalSize(maintenanceFundsBusinessInfo.getTotalInvolvedArea());
        accountMain.setAreaId(maintenanceFundsBusiness.getAreaId());
        // 二次拨付生成财务流水异常2023/07/24
        // 查询银行信息
        GwjFinanceBank bank = remoteGwjFinanceService.selectFinanceBankByBankIdAndAreaId(maintenanceFundsBusinessInfo.getBankId(), maintenanceFundsBusiness.getAreaId(), SecurityConstants.INNER).getData();
        if (ObjectUtil.isEmpty(bank)) {
            throw new ServiceException("未查询到对应开户行信息");
        }
        // 赋值银行主键
        accountMain.setBankId(maintenanceFundsBusinessInfo.getBankId());
        // 赋值银行账户类型
        accountMain.setBankAccountType(String.valueOf(bank.getBankAccountType()));
        try {
            R<Integer> r = remoteGwjFinanceService.insertGwjFinanceAccountMain(accountMain, SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData()) || ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), r.getData())) {
                throw new ServiceException("新增总账流水异常");
            }
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjFinanceService][insertGwjFinanceAccountMain]异常: [{}]", e);
            throw new ServiceException("远程调用 -> [remoteGwjFinanceService][insertGwjFinanceAccountMain]异常");
        }
        Optional.ofNullable(((IGwjMaintenanceFundsBusinessService)AopContext.currentProxy()).updateGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusiness() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
                setFinancialJournalFlag(FlagStatusEnum.SUC.getCode());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException("GwjMaintenanceFundsBusiness更新异常");
        });
        return FlagStatusEnum.SUC.getCode();
    }

    @Override
    public List<GwjFinanceAccountMain> selectGwjFinanceAccountMainList(RemoteGwjFinanceAccountMainRequest mainRequest) {
        GwjFinanceAccountMain accountMain = new GwjFinanceAccountMain();
        BeanUtil.copyProperties(mainRequest, accountMain);
        try {
            R<List<GwjFinanceAccountMain>> r = remoteGwjFinanceService.selectGwjFinanceAccountMainList(accountMain, SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData()) || CollectionUtil.isEmpty(r.getData())) {
                throw new ServiceException("数据为空");
            }
            return r.getData().stream().map(item -> {
                item.setBizFlagIdStr(GwjBusinessFlagType.getInfoByCode(item.getBizFlagId()));
                item.setCheckTypeStr(GwjCheckAccountType.getInfoByCode(item.getCheckType()));
                item.setCheckStatusStr(GwjCheckAccountStatus.getInfoByCode(item.getCheckStatus()));
                return item;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjFinanceService][selectGwjFinanceAccountMainList]异常: [{}]", e);
            return null;
        }
    }

    @Override
    public PreAcceptSubmitMessage getBusinessModules(Long bizId) {
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(bizId);
        if (ObjectUtil.isNull(maintenanceFundsBusiness)) {
            throw new ServiceException("GwjMaintenanceFundsBusiness为空");
        }
        GwjMaintenanceFundsBusinessInfo maintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(maintenanceFundsBusiness.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessInfo)) {
            throw new ServiceException("GwjMaintenanceFundsBusinessInfo为空");
        }
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(maintenanceFundsBusiness.getBizId());
        if (ObjectUtil.isNull(maintenanceFundsBusinessCommunity)) {
            throw new ServiceException("GwjMaintenanceFundsBusinessCommunity为空");
        }
        List<GwjMaintenanceFundsBusinessHouse> maintenanceFundsBusinessHouseList = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessHouseList)) {
            throw new ServiceException("List<GwjMaintenanceFundsBusinessHouse>为空");
        }
        List<GwjMaintenanceFundsBusinessBuild> maintenanceFundsBusinessBuildList = maintenanceFundsBusinessBuildService.selectGwjMaintenanceFundsBusinessBuildList(new GwjMaintenanceFundsBusinessBuild() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessBuildList)) {
            throw new ServiceException("List<GwjMaintenanceFundsBusinessBuild>为空");
        }
        List<GwjMaintenanceFundsBusinessOwner> maintenanceFundsBusinessOwnerList = maintenanceFundsBusinessOwnerService.selectGwjMaintenanceFundsBusinessOwnerList(new GwjMaintenanceFundsBusinessOwner() {
            {
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        });
        if (CollectionUtil.isEmpty(maintenanceFundsBusinessOwnerList)) {
            throw new ServiceException("GwjMaintenanceFundsBusinessOwner为空");
        }
        List<GwjMaintenanceFundsBusinessAttachment> maintenanceFundsBusinessAttachmentList = maintenanceFundsBusinessAttachmentService.selectGwjMaintenanceFundsBusinessAttachmentList(new GwjMaintenanceFundsBusinessAttachment() {
            {
                setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
            }
        });

        PreAcceptSubmitMessage acceptSubmitMessage = new PreAcceptSubmitMessage() {
            {
                setMaintenanceFundsBusiness(maintenanceFundsBusiness);
                setMaintenanceFundsBusinessInfo(maintenanceFundsBusinessInfo);
                setMaintenanceFundsBusinessCommunity(maintenanceFundsBusinessCommunity);
                setMaintenanceFundsBusinessBuildList(maintenanceFundsBusinessBuildList);
                setMaintenanceFundsBusinessHouseList(maintenanceFundsBusinessHouseList);
                setMaintenanceFundsBusinessOwnerList(maintenanceFundsBusinessOwnerList);
                setMaintenanceFundsBusinessAttachmentList(maintenanceFundsBusinessAttachmentList);
            }
        };
        return acceptSubmitMessage;
    }

    /**
     * 导出房屋数据
     *
     * @param allocatedAmountRequest
     * @return 楼栋下房屋信息
     */
    @Override
    public List<AllocatedAmountListDTO> exportHouseList(AllocatedAmountRequest allocatedAmountRequest) {
        return maintenanceFundsBusinessHouseService.allocatedAmountList(allocatedAmountRequest);
    }

    /**
     * 分摊清册
     *
     * @return {@link List}<{@link CostListDTO}>
     */
    @Override
    public List<CostListDTO> costList(Long bizId) {
        return maintenanceFundsBusinessMapper.costList(bizId);
    }

    /**
     * 打印备案证明
     *
     * @param bizId 业务标识
     * @return {@link FilingCertificateDTO}
     */
    @Override
    public FilingCertificateDTO printFilingCertificate(Long bizId) {
        FilingCertificateDTO filingCertificateDTO = maintenanceFundsBusinessMapper.printFilingCertificate(bizId);
        if (ObjectUtil.isNull(filingCertificateDTO)) {
            throw new ServiceException("filingCertificateDTO为空");
        }
        GwjMaintenanceFundsBusinessCommunity maintenanceFundsBusinessCommunity = maintenanceFundsBusinessCommunityService.selectGwjMaintenanceFundsBusinessCommunityByBusinessId(bizId);
        List<GwjMaintenanceFundsBusinessHouse> houseList = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setSelectFlag(SelectFlagEnum.SELECT.getCode());
                setBizId(bizId);
            }
        });

        filingCertificateDTO.setCommunityName(maintenanceFundsBusinessCommunity.getCommunityName());
        filingCertificateDTO.setTime(LocalDate.now());
        filingCertificateDTO.setShareHouseholds(filingCertificateDTO.getTotalHouseholds());
        filingCertificateDTO.setMaintenanceProject(maintenanceFundsBusinessCommunity.getCommunityName());
        switch (BusinessTypeEnum.transfer(filingCertificateDTO.getType())) {
            case FORMAL:
                filingCertificateDTO.setApplicationMaterials(FilingCertificateEnum.USE_APPLICATION.getMsg());
                break;
            case URGENT_FORMAL:
                filingCertificateDTO.setApplicationMaterials(FilingCertificateEnum.URGENT_USE_APPLICATION.getMsg());
                break;
            default:
                throw new ServiceException("业务类型不正确");
        }
        // 实时查询当前小区所有的当前余额
        filingCertificateDTO.setTotalMoney(BigDecimal.ZERO);
        // 查询涉及用户的面积
        filingCertificateDTO.setPartialPortionArea(BigDecimal.ZERO);
        // 实时查询涉及用户的当前余额
        filingCertificateDTO.setProprietaryPortionMoney(BigDecimal.ZERO);
        List<GwjBaseHouse> baseHouseList = baseHouseService.selectGwjBaseListByCommunityId(maintenanceFundsBusinessCommunity.getCommunityId());
        if (CollectionUtil.isNotEmpty(baseHouseList)) {
            filingCertificateDTO.setTotalMoney(baseHouseList.stream().map(GwjBaseHouse::getCurrentMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
            List<GwjBaseHouse> portionBaseHouseList = baseHouseList.stream().filter(item -> houseList.stream().map(GwjMaintenanceFundsBusinessHouse::getHouseCode).collect(Collectors.toList()).contains(item.getHouseCode())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(baseHouseList)) {
                filingCertificateDTO.setProprietaryPortionMoney(portionBaseHouseList.stream().map(GwjBaseHouse::getCurrentMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
                filingCertificateDTO.setPartialPortionArea(portionBaseHouseList.stream().map(baseHouse -> ObjectUtil.equal(BigDecimal.ZERO, baseHouse.getActualSize()) ? baseHouse.getForecastSize() : baseHouse.getActualSize()).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
        return filingCertificateDTO;
    }

    /**
     * 内部获取公维金维修资金业务
     *
     * @param bizId 业务主键
     * @return
     */
    @Override
    public GwjMaintenanceFundsBusinessInner innerGetInfo(Long bizId) {
        return maintenanceFundsBusinessMapper.innerGetInfo(bizId);
    }

    /**
     * 查询业主征求意见材料-房屋业主投票列表
     *
     * @param outServerIdentification 业务标识
     * @return
     */
    @Override
    public List<GwjExpendHouseAndOwnerDTO> selectHouseAndOwnerVoteInfo(String outServerIdentification) {
        return remoteGwjExpendService.selectHouseAndOwnerVoteInfo(outServerIdentification, SecurityConstants.INNER).getData();
    }

    /**
     * 修改公维金维修资金业务
     *
     * @param gwjMaintenanceFundsBusiness 公维金维修资金业务
     * @return
     */
    @Override
    public GwjMaintenanceFundsBusiness updateGwjMaintenanceFundsBusinessInner(GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness) {
        if (ObjectUtil.notEqual(maintenanceFundsBusinessMapper.updateGwjMaintenanceFundsBusiness(gwjMaintenanceFundsBusiness), FlagStatusEnum.SUC.getCode())) {
            return null;
        }
        return maintenanceFundsBusinessMapper.selectGwjMaintenanceFundsBusinessByBusinessId(gwjMaintenanceFundsBusiness.getBizId());
    }

    /**
     * 获取申请报批信息-业主表决情况
     *
     * @param outServerIdentification 外网业务标识
     * @return
     */
    @Override
    public JSONObject getApplication4ApprovalOwnerCheck(String outServerIdentification, Integer bizFlagId) {
        return remoteGwjExpendService.ownerCheckInner(outServerIdentification, bizFlagId, SecurityConstants.INNER).getData();
    }

    /* (non-Javadoc)
     * @see com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessService#preAcceptExamineByBizId(java.lang.Long)
     */
    @Override
    public MqSendResult preAcceptExamineByBizId(Long bizId) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 步骤回调
     *
     * @param business
     * @return
     */
    public String resultNotify(GwjMaintenanceFundsBusiness business) {
        // 设置回调参数
        PreAcceptMessage preAcceptMessage = new PreAcceptMessage();
        preAcceptMessage.setAcceptTime(LocalDateTime.now());
        preAcceptMessage.setStepId(business.getStepId());
        preAcceptMessage.setOperId(SecurityUtils.getLoginUser().getUserid());
        preAcceptMessage.setOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
        preAcceptMessage.setServerIdentification(business.getServerIdentification());
        preAcceptMessage.setOutServerIdentification(business.getOutServerIdentification());
        return JSONUtil.toJsonStr(preAcceptMessage);
    }

    // ---------------------------------------新增功能区 hmh start--------------------------------------------------
    /*
     * 新增公维金维修资金业务 20230714
     */
    @Override
    public int insertGwjMaintenanceFundsBusinessCustom(GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness) {
        gwjMaintenanceFundsBusiness.setCurrentOperId(SecurityUtils.getLoginUser().getUserid());
        gwjMaintenanceFundsBusiness.setCurrentOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
        gwjMaintenanceFundsBusiness.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
        gwjMaintenanceFundsBusiness.setCreateTime(DateUtils.getNowDate());
        return maintenanceFundsBusinessMapper.insertGwjMaintenanceFundsBusinessCustom(gwjMaintenanceFundsBusiness);
    }

    /*
     * 修改公维金维修资金业务 20230714
     */
    @Override
    public int updateGwjMaintenanceFundsBusinessCustom(GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness) {
        gwjMaintenanceFundsBusiness.setCurrentOperId(SecurityUtils.getLoginUser().getUserid());
        gwjMaintenanceFundsBusiness.setCurrentOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
        gwjMaintenanceFundsBusiness.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
        gwjMaintenanceFundsBusiness.setUpdateTime(DateUtils.getNowDate());
        return maintenanceFundsBusinessMapper.updateGwjMaintenanceFundsBusinessCustom(gwjMaintenanceFundsBusiness);
    }

    /*
     * 批量取消收件 20230717
     */
    @Override
    public int batchCancelReceipt(Long[] attachmentId) {
        return maintenanceFundsBusinessAttachmentService.updateGwjMaintenanceFundsBusinessAttachment(new GwjMaintenanceFundsBusinessAttachment() {
            {
                // setAttachmentId(attachmentId);
                setReceiveFlag(FlagStatusEnum.FAL.getCode());
            }
        });
    }

    /**
     * 财务对账
     *
     * @param bizId 业务主键
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean financeCheck(Long bizId) {
        // 查询业务信息
        GwjMaintenanceFundsBusiness gwjMaintenanceFundsBusiness = this.getGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusinessRequest() {
            {
                // 赋值业务主键
                setBizId(bizId);
            }
        });
        // 判断业务信息是否为空
        if (ObjectUtil.isEmpty(gwjMaintenanceFundsBusiness)) {
            throw new ServiceException("未查询到对应业务信息");
        }
        // 查询业务详情
        GwjMaintenanceFundsBusinessInfo gwjMaintenanceFundsBusinessInfo = maintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        // 判断业务详情是否为空
        if (ObjectUtil.isEmpty(gwjMaintenanceFundsBusinessInfo)) {
            throw new ServiceException("未查询到对应业务详情信息");
        }
        // 判断是否为二次拨付
        if (!AppropriationWayEnum.TWO.getCode().equals(gwjMaintenanceFundsBusinessInfo.getAppropriationWay())) {
            throw new ServiceException("当前业务非二次补件业务，请重新受理");
        }
        // 校验业务步骤
        if (!BusinessStatusEnum.FINANCE_CHECK.getCode().equals(gwjMaintenanceFundsBusiness.getStatus())) {
            throw new ServiceException("当前业务步骤不一致，请勿进行财务对账");
        }
        // 校验实际拨出金额是否为空
        if (ObjectUtil.isEmpty(gwjMaintenanceFundsBusinessInfo.getActualAllocatedSettlementAmount())) {
            throw new ServiceException("实际拨出金额不能为空");
        }
        // 赋值0
        BigDecimal zero = new BigDecimal("0.00");
        // 校验预算拨出金额是否为空
        if (ObjectUtil.isEmpty(gwjMaintenanceFundsBusinessInfo.getBudgetAppropriationAmount()) && zero.compareTo(gwjMaintenanceFundsBusinessInfo.getBudgetAppropriationAmount()) < 0) {
            throw new ServiceException("预算拨出金额不能为空且预算拨出金额不能为0");
        }
        // 赋值预算拨出金额一半
        BigDecimal halfBudgetAppropriationAmount = gwjMaintenanceFundsBusinessInfo.getBudgetAppropriationAmount().multiply(new BigDecimal("0.5"));
        // 校验实际拨出金额是否为大于0小于等于预算拨出金额的50%
        if (!(zero.compareTo(gwjMaintenanceFundsBusinessInfo.getActualAllocatedSettlementAmount()) < 0 && halfBudgetAppropriationAmount.compareTo(gwjMaintenanceFundsBusinessInfo.getActualAllocatedSettlementAmount()) >= 0)) {
            throw new ServiceException("实际拨出金额必须大于0且小于或等于预算拨出金额的50%");
        }
        // 判断该业务是否已经完成财务对账
        if (GwjCheckAccountStatus.CHECK_SUCCESS.getCode().equals(String.valueOf(gwjMaintenanceFundsBusiness.getFinanceCheck()))) {
            throw new ServiceException("已完成财务对账请勿重复提交");
        }
        // 更新财务对账状态
        gwjMaintenanceFundsBusiness.setFinanceCheck(Integer.valueOf(GwjCheckAccountStatus.CHECK_SUCCESS.getCode()));
        GwjMaintenanceFundsBusiness business = this.updateGwjMaintenanceFundsBusiness(gwjMaintenanceFundsBusiness);
        if (ObjectUtil.isEmpty(business)) {
            throw new ServiceException("财务对账失败");
        }
        // 查询总账流水
        try {
            R<GwjFinanceAccountMain> r = remoteGwjFinanceService.selectGwjFinanceAccountMainByBizId(bizId, SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData()) || ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), r.getData())) {
                throw new ServiceException("未查询到对应总账流水信息");
            }
            // 更新总账流水数据
            R<Integer> editR = remoteGwjFinanceService.updateGwjFinanceAccountMain(new GwjFinanceAccountMain() {
                {
                    setBizId(business.getBizId());
                    setCheckStatus(GwjCheckAccountStatus.CHECK_SUCCESS.getCode());
                    setCheckTime(DateUtils.getNowDate());
                }
            }, SecurityConstants.INNER);
            if (R.isError(editR)) {
                throw new ServiceException(editR.getMsg());
            }
            if (ObjectUtil.isNull(editR.getData()) || ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), editR.getData())) {
                throw new ServiceException("未查询到对应总账流水信息");
            }
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjFinanceService][insertGwjFinanceAccountMain]异常: [{}]", e);
            throw new ServiceException("远程调用 -> [remoteGwjFinanceService][insertGwjFinanceAccountMain]异常");
        }
        return Boolean.TRUE;
    }

    /**
     * 基础房屋扣费（案例完结）
     *
     * @param bizId 业务主键
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean baseHouseCharging(Long bizId) {
        // 查询业务房屋信息
        List<GwjMaintenanceFundsBusinessHouse> gwjMaintenanceFundsBusinessHouses = maintenanceFundsBusinessHouseService.selectGwjMaintenanceFundsBusinessHouseList(new GwjMaintenanceFundsBusinessHouse() {
            {
                setBizId(bizId);
                // 查询选中状态房屋
                setSelectFlag(1);
            }
        });
        // 判断业务房屋数据是否为空
        if (ObjectUtil.isEmpty(gwjMaintenanceFundsBusinessHouses)) {
            throw new ServiceException("基础房屋扣费失败，未查询到对应业务房屋信息");
        }
        // 业务房屋信息实际扣款金额转Map
        Map<Long, BigDecimal> actualAllocationMoneyMap = gwjMaintenanceFundsBusinessHouses.stream().collect(Collectors.toMap(GwjMaintenanceFundsBusinessHouse::getHouseId, GwjMaintenanceFundsBusinessHouse::getActualAllocationMoney));
        // 将业务房屋信息转换为基础房屋主键
        Long[] houseIds = gwjMaintenanceFundsBusinessHouses.stream().map(GwjMaintenanceFundsBusinessHouse::getHouseId).toArray(Long[]::new);
        // 查询基础房屋信息
        List<GwjBaseHouse> baseHouses = baseHouseService.selectGwjBaseHoseByHouseIds(houseIds);
        // 判断基础房屋数据是否为空
        if (ObjectUtil.isEmpty(baseHouses)) {
            throw new ServiceException("基础房屋扣费失败，未查询到对应基础房屋信息");
        }
        // 扣除基础房屋款项
        baseHouses = baseHouses.stream().map(item -> {
            // 判断房屋余额是否为空
            if (ObjectUtil.isEmpty(item.getCurrentMoney())) {
                throw new ServiceException("房屋编号为" + item.getHouseCode() + "可用余额为空");
            }
            // 计算房屋可用余额
            BigDecimal useableCurrentMoney = item.getCurrentMoney().subtract(ObjectUtil.isEmpty(item.getBlockedMoney()) ? BigDecimal.ZERO : item.getBlockedMoney());
            // 判断房屋可用余额是否大于零
            if (useableCurrentMoney.compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("房屋编号为" + item.getHouseCode() + "可用余额不足");
            }
            // 获取扣款金额
            BigDecimal actualAllocationMoney = actualAllocationMoneyMap.get(item.getHouseId());
            // 判断扣款金额是否为空
            if (ObjectUtil.isNotEmpty(actualAllocationMoney)) {
                // 判断房屋可用余额是否小于于扣款金额
                if (useableCurrentMoney.compareTo(actualAllocationMoney) < 0) {
                    throw new ServiceException("房屋编号为" + item.getHouseCode() + "可用余额不足,房屋可用余额小于业务扣款金额");
                }
                // 房屋可用余额扣除扣款金额并且加上冻结金额
                BigDecimal newCurrentMoney = useableCurrentMoney.subtract(actualAllocationMoney).add(item.getBlockedMoney());
                // 赋值基础房屋当前余额
                item.setCurrentMoney(newCurrentMoney);
            }
            return item;
        }).collect(Collectors.toList());
        // 更新业务基础房屋信息
        if (0 >= baseHouseService.updateBatchGwjBaseHouse(baseHouses)) {
            throw new ServiceException("基础房屋扣费更新异常");
        }
        return Boolean.TRUE;
    }
    // ---------------------------------------新增功能区 hmh end--------------------------------------------------

}
